Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a file uca.xml (Thunar configuration for custom actions):

<?xml encoding="UTF-8" version="1.0"?>
<actions>
<action>
    <!--some code-->
</action>
</actions>
<--blank line here-->

Mind that the file ends with a blank line

I want a bash command/script to insert a file customAction.txt containing:

<action>
    <!--custom configuration-->
</action>

so it will end looking like:

<?xml encoding="UTF-8" version="1.0"?>
<actions>
<action>
    <!--some code-->
</action>
<action>
    <!--custom configuration-->
</action>
</actions>

I tried a method given by jfgagne:

sed -n -i -e '/<\/actions>/r customAction.txt' -e 1x -e '2,${x;p}' -e '${x;p}' uca.xml

but it works only if there is at least one character (not a blank line) inserted below the tag.

My temporary workaround is a script:

echo "someDummyText" >> uca.xml
sed -n -i -e '/<\/actions>/r customaction.txt' -e 1x -e '2,${x;p}' -e '${x;p}' uca.xml
sed -i 's/someDummyText//' uca.xml
sed -i '${/^$/d;}' uca.xml

but I believe there is a more elegant, one-line solution with sed. Thanks in advance.

Note: this is my very post to the U&L and StackExchange community, so please be lenient with me and do not hesitate to correct me verbosely if I did something wrong. I read the SE FAQ and tried to search for an answer elsewhere with not much luck.

share|improve this question
    
If you read all the answers there you will find that you could easily do that via awk/perl/ed. Why do you insist on using sed ? – don_crissti Mar 31 at 14:02
up vote 0 down vote accepted

I think your solution is perfectly adequate. You can optimise it a bit by replacing the last 2 seds with just one:

sed -i '$d' uca.xml

After all, you just put the extra line there, so you know what you are removing.


If you are looking for alternative solutions, you can use sed to get the line number of the pattern match, and then use that -1 to do the read:

if lno=$(sed -n -e '/<\/actions>/=' uca.xml)
then let lno=lno-1
     sed  -i -e "$lno"'r customaction.txt' uca.xml
fi

or if you like the ancient but serviceable ed command you can do

ed -s uca.xml <<\!
?</actions>
-1r customaction.txt
w
q
!
share|improve this answer
    
Haven't tried third option with ed but first two options work as expected. Thank you. – mDfRg Apr 1 at 20:04

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.