What unix command can we use to append some text t

2019-02-28 10:40发布

问题:

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

回答1:

Perl:

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

$. is the line number



回答2:

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


回答3:

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.



回答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


回答5:

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


回答6:

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