The text file manipulation is one of the most common job for a system administrator, today I'm going to show how to append a string to each line of a text file.

The problem:
we have a file named file0.txt and we want to append the string "text to append" to each line of this file.

$ cat file0.txt 
1
2
3
4
5
6

we want an output like the following:

$ cat output.txt 
1text to append
2text to append
3text to append
4text to append
5text to append
6text to append

shell1

 

 

1 – The awk

awk can do almost everything on text files, here you are the awk solution for our problem

$ awk '{ print $0 "text to append" }' < file0.txt > file1.txt

$ cat file1.txt 
1text to append
2text to append
3text to append
4text to append
5text to append
6text to append

2 – Sed, the other side of the moon


$ sed 's/$/text to append/' file1.txt > file2.txt

$ cat file2.txt 
1text to appendtext to append
2text to appendtext to append
3text to appendtext to append
4text to appendtext to append
5text to appendtext to append
6text to appendtext to append


3 – perl scripting language


$perl -ne 'chomp; printf "%stext to append\n", $_' file2.txt > file3.txt

$ cat file3.txt 
1text to appendtext to appendtext to append
2text to appendtext to appendtext to append
3text to appendtext to appendtext to append
4text to appendtext to appendtext to append
5text to appendtext to appendtext to append
6text to appendtext to appendtext to append


4 – laminate files
I discovered this command some weeks ago, and I can say it can be used with success for this kind of problems

$lam file3.txt -s "text to append" > file4.txt

1text to appendtext to appendtext to appendtext to append
2text to appendtext to appendtext to appendtext to append
3text to appendtext to appendtext to appendtext to append
4text to appendtext to appendtext to appendtext to append
5text to appendtext to appendtext to appendtext to append
6text to appendtext to appendtext to appendtext to append

See you soon

Gg1