1

Does anyone know of a series of unix commands that allows someone to append some text to the end of a specific line in a file?

eg

Line 1

Line 2

Line 3

Line 4

I wish to append the text ", extra information" to Line 3 so that the File will now look like this:

Line 1

Line 2

Line 3, extra information

Line 4

0

6 Answers 6

8

in awk it's:

awk '{s=$0; if( NR==3 ){ s=s ", Extra Information" } print s;}' myfile > newfile

proper sed version:

sed -e '3s/$/, Extra Information/' -i myfile
Sign up to request clarification or add additional context in comments.

Comments

5

Here is a version with portable sed (without -i option):

sed '3s/$/Hello World/' myfile

Note that myfile is not modified, so you can recover from possible mistakes.

6 Comments

superfluous use of cat! Oh noes!
sed -i '3s/$/Hello World/' myfile is better
This won't actually change "myfile".
From the sed(1) man page of Mac OS X 10.5.6: "The -E, -a and -i options are non-standard FreeBSD extensions and may not be available on other operating systems." So for maximum portability, I didn't suggest inline modifications.
If you don't want to use -i, then at least explain why your answer doesn't do what the question asks.
|
4
awk 'NR == 3 { print $0 ", extra information" } NR != 3' myfile

The part before the braces is the condition: If we are in line 3, we append some text. If braces are omitted, the default action is to just print out $0. Redirect to a new file or pipe to another program as appropriate. You cannot redirect to the same file you are just reading. A common workaround is to redirect to a new file, and then move over if the command was successful:

somecommand > oldfile.tmp && mv oldfile.tmp oldfile

2 Comments

i've nothing to add to his answer :) i like the linked blog entry about linkage too.
2

Perl:

perl -p -e's{\n}{, extra information\n} if $. ==3' myfile

$. is the line number

Comments

2
sed -e "s/^Line 3/\0, extra info/" -i text.txt

2 Comments

I think he means by line number, not line content.
I got that ... doesn't matter, now he knows both ways ;-)
1

If you want the extra information to be appended to just one line, any of the sed/awk one-liners will do.

If you want to append something to (almost) every line in the file, you should create a second file with the extra information for each line and use paste:

$ cat myfile
line 1
line 2
line 3
line 4
$ cat extra 
something

something else
$ paste myfile extra
line 1  something
line 2
line 3  something else
line 4

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.