bash : inexplicable behavior sed

2019-09-09 07:15发布

问题:

I wrote a quite simple bash script as :

#!/bin/bash

nLine=$(awk '/text_to_parse/{ print NR; exit }' testFile.xml)
echo "LINE = $nLine"
sed -e "${nLine}s/.*/new text/" < testFile.xml
echo 
cat testFile.xml

exit 0

the execution returns :

LINE = 8
<Test>
    <Name>First Test</Name>
    <Version>1.0</Version>        
    <Command>new text</Command>
</Test>

<Test>
    <Name>First Test</Name>
    <Version>1.0</Version>        
    <Command>text_to_parse</Command>
</Test>

The modification is never applied. The file can be modified ..

 -rwxrwxrwx 1 root root  290 Jan  1 00:23 testFile.xml

回答1:

Your whole script should be rewritten as this one command:

sed -i 's/.*text_to_parse.*/new text/' testFile.xml
cat testFile.xml

You'll need to provide a param to -i in some seds.



回答2:

Not quite sure how is Line = 8. But then if i understand the requirement correctly, it is to replace the first line that has the text. You can also do the below:
sed -i '/text_to_parse/{s/.*/new text/;:a;n;ba}' testFile.xml OR
sed -i '0,/text_to_parse/{/text_to_parse/s/.*/new text/}' testFile.xml