olo olo - 4 months ago 24
Linux Question

sed, replacing first occurrence match of the first line

my text looks like below

this This that
it It Its
my My Mine
this This that
it It Its
my My Mine


I want to replace the first line of the first occurrence match. eg. match the line which contains
my
then replace the line. I did

cat txt|sed "0,/my/c\my changed line" txt


The print off looks below, the first 2 line are trimmed.

my changed line
this This that
it It Its
my My Mine


if I run this
cat txt|sed "s/my/changeline/" txt


The output is below

this This that
it It Its
changeline My Mine
this This that
it It Its
changeline My Mine


How can I get the result like below?

this This that
it It Its
changeline My Mine
this This that
it It Its
my My Mine

Answer

Using sed:

sed '0,/.*my.*/s//my changed line/' file

What this does, in the range of 0,/.*my.*/ it will replace the matched .*my.* with "my changed line".

An equivalent slightly easier to understand version of the same thing:

sed '0,/my/{/.*my.*/s//my changed line/}' file

Using awk the logic is slightly easier to understand:

awk '!/my/ || seen { print } /my/ && !seen { print "my changed line"; seen = 1 }' file