I am doing a find and replace with sed, replacing the BASH variable $a
(when at the start of a new line) with the BASH variable $b
:
This might work for you:
sed -i 'x;/^./{x;b};x;/^'"$a"'/{s//'"$b"'/;h}' file
Or:
sed -i ':a;$!{N;ba};s/^'"$a/$b"'/m' file
This should work:
sed -i "0,/^\$a/s//\$b/" ./file.txt
You can read more about this at http://www.grymoire.com/Unix/Sed.html#toc-uh-29
One way using sed
:
sed "s/^$var1/$var2/ ; ta ; b ; :a ; N ; ba" infile
Explanation:
s/^$var1/$var2/ # Do substitution.
ta # If substitution succeed, go to label `:a`
b # Substitution failed. I still haven't found first line to
# change, so read next line and try again.
:a # Label 'a'
N # At this position, the substitution has been made, so begin loop
# where I will read every line and print until end of file.
ba # Go to label 'a' and repeat the loop until end of file.
A test with same example provided by Jaypal:
Content of infile
:
ab aa
ab ff
baba aa
ab fff
Run the command:
sed "s/^$var1/$var2/ ; ta ; b ; :a ; N ; ba" infile
And result:
bb aa
ab ff
baba aa
ab fff