How to append to the first line of a file?

6

1

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

tarabyte

Posted 2016-01-29T00:06:45.430

Reputation: 1 151

Answers

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"

Pimp Juice IT

Posted 2016-01-29T00:06:45.430

Reputation: 29 425

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.

Tiw

Posted 2016-01-29T00:06:45.430

Reputation: 217

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.

davidgo

Posted 2016-01-29T00:06:45.430

Reputation: 49 152