Monday, 26 May 2014

SED how to replace sample in only first/last n lines of file Linux SOLVED

Recently I came across this problem. I had to find in config file where settings for something is located. I only know that I had do change words "right" to "left" somewhere in that file that have more than 4000 lines and that in that file in 70 lines there are line that have right inside.

With SED I replace all "right" with "left" so I do know that is somewhere in there but what line exactly?

Real question is how to replace one pattern with other but not in whole file but in for example 2 first lines so that you can narrow your search for that particular line?!?

Here is one solution for this problem!

root@ubuntus1:~#for i in `grep -n text1 sample.txt|head -2|awk -F: '{print $1}'`;do sed -i "$i s/text/test/g" sample.txt;done

Here are explanation!
Content of sample.txt file is

root@ubuntus1:~# cat sample.txt
text11
text21
text12
text22
text13
text23
text14
text24
text15
text25

and you want to replace first two appearance of pattern text with test in lines where there is text1 pattern.
After executing above line result is

root@ubuntus1:~# cat sample.txt
test11
text21
test12
text22
text13
text23
text14
text24
text15
text25










Maybe there is more elegant solution for this but this works for me.

No comments: