views:

2144

answers:

6

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

+4  A: 

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.

mouviciel
superfluous use of cat! Oh noes!
Joachim Sauer
sed -i '3s/$/Hello World/' myfile is better
Johannes Weiß
This won't actually change "myfile".
Paul Tomblin
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.
mouviciel
If you don't want to use -i, then at least explain why your answer doesn't do what the question asks.
Paul Tomblin
Paul Tomblin
+2  A: 
sed -e "s/^Line 3/\0, extra info/" -i text.txt
Joachim Sauer
I think he means by line number, not line content.
Ryan Graham
I got that ... doesn't matter, now he knows both ways ;-)
Joachim Sauer
+5  A: 

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
sfossen
+2  A: 
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
Johannes Schaub - litb
have a look at qn http://stackoverflow.com/questions/598143/explain-about-linkagesexternal-internal-in-c/598180#598180
yesraaj
i've nothing to add to his answer :) i like the linked blog entry about linkage too.
Johannes Schaub - litb
+2  A: 

Perl:

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

$. is the line number

mirod
+1  A: 

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
Roberto Bonvallet