Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed replace string in a first line

How can I replace a string but only in the first line of the file using the program "sed"?

The commands s/test/blah/1 and 1s/test/blah/ don't seem to work. Is there another way?

like image 361
irek Avatar asked Sep 21 '12 07:09

irek


2 Answers

This might work for you (GNU sed):

sed -i '1!b;s/test/blah/' file

will only substitute the first test for blah on the first line only.

Or if you just want to change the first line:

sed -i '1c\replacement' file 
like image 191
potong Avatar answered Oct 26 '22 17:10

potong


This will do it:

sed -i '1s/^.*$/Newline/' textfile.txt

Failing that just make sure the match is unique to line one only:

sed -i 's/this is line one and its unique/Changed line one to this string/' filename.txt

The -i option writes the change to the file instead of just displaying the output to stdout.

EDIT:

To replace the whole line by matching the common string would be:

sed -i 's/^.*COMMONSTRING$/Newline/'

Where ^ matches the start of the line, $ matches the end of the line and .* matches everything upto COMMONSTRING

like image 22
Chris Seymour Avatar answered Oct 26 '22 17:10

Chris Seymour