6

How can you use sed to replace the entire first line of a file with that first line plus some additional text? For example, how can I append -foo to a file that contains only one line.

testfile contents start:

some-text

testfile contents end:

some-text-foo
4

How to append to the first line of a file?

How can you use sed to replace the entire first line of a file with that first line plus some additional text?

Here's another way to append a string to the end of line number 1 with SED on Windows then convert it back to DOS format for EOL characters i.e. CRLF rather than LF...

First Command (append characters -foo to end of first line only)

SED -i "1 s|$|-foo|" "C:\Path\testfile.txt"

Second Command (convert EOL back to carriage return line feed)

SED -i "s/$/\r/" "C:\Path\testfile.txt"
2
sed '1{s/$/-foo/}' file

1 for first line, you can use num,num to assign range, eg 3,5 is change line 3 to line 5. s for substitute, $ means the end of the line. If you want change the file right away, use -i parameter, anyway, use it with caution.

awk 'FNR==1{print $0 "-foo";}' file(s)

awk is more powerful, but don't have -i parameter to change file right away.

1

You can do this with

sed -i '1!b;s/$/\-foo/g' testfile

This takes the file, looks at the first line only (1!b;) looks for the end of line ($) and replaces it with the string you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.