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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With