Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Command to insert lines before first match

Tags:

linux

sed

awk

I have file with the below info

testing
testing
testing

I want to insert a word(tested) before the first testing word using sed or any linux command

need to get output like

tested
testing
testing
testing

Thanks

like image 352
Ravikanth Avatar asked May 22 '15 00:05

Ravikanth


2 Answers

For lines consisting of "testing" exactly:

sed '0,/^testing$/s/^testing$/tested\n&/' file

For lines containing "testing":

sed '0,/.*testing.*/s/.*testing.*/tested\n&/' file

For Lines Starting with "testing"

sed '0,/^testing.*/s/^testing.*/tested\n&/' file

For lines ending with "testing":

sed '0,/.*testing$/s/.*testing$/tested\n&/' file

To update the content of the file with the result add "-i", example:

sed -i '0,/testing/s/testing/tested\n&/' file
like image 162
Yahya Yahyaoui Avatar answered Oct 12 '22 22:10

Yahya Yahyaoui


This might work for you (GNU sed):

sed -e '/testing/{itested' -e ':a;n;ba}' file

Insert tested before the first match of testing and then use a loop to read/print the remainder of the file.

Or use the GNU specific:

sed '0,/testing/itested' file
like image 25
potong Avatar answered Oct 12 '22 21:10

potong