How to append to the first line of a file?

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"

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.

Tags:

Sed