The text file manipulation is one of the most common job for a system administrator, today I'm going to show how to insert a string at the beginning of each line in a text file.
The problem:
we have a file named file0.txt and we want to add the string "text to add at the beginning" at the beginning of each line of this file.
$ cat file0.txt
1
2
3
4
5
6
we want an output like the following:
$ cat output.txt
text to add at the beginning1
text to add at the beginning2
text to add at the beginning3
text to add at the beginning4
text to add at the beginning5
text to add at the beginning6
1 – The awk
awk can do almost everything on text files, here you are the awk solution for our problem, this sites has a lot of example of text files manipulation using awk.
$ awk '{print "text to add at the beginning"$0}' file0.txt > file1.txt $ cat file1.txt text to add at the beginning1 text to add at the beginning2 text to add at the beginning3 text to add at the beginning4 text to add at the beginning5 text to add at the beginning6
2 – Sed, the other side of the moon
$ sed 's/^/text to add at the beginning/' file1.txt > file2.txt $ cat file2.txt text to add at the beginningtext to add at the beginning1 text to add at the beginningtext to add at the beginning2 text to add at the beginningtext to add at the beginning3 text to add at the beginningtext to add at the beginning4 text to add at the beginningtext to add at the beginning5 text to add at the beginningtext to add at the beginning6
3 – perl scripting language
$ perl -e 'while (<>) {print "text to add at the beginning$_"}' < file2.txt > file3.txt $ cat file3.txt text to add at the beginningtext to add at the beginningtext to add at the beginning1 text to add at the beginningtext to add at the beginningtext to add at the beginning2 text to add at the beginningtext to add at the beginningtext to add at the beginning3 text to add at the beginningtext to add at the beginningtext to add at the beginning4 text to add at the beginningtext to add at the beginningtext to add at the beginning5 text to add at the beginningtext to add at the beginningtext to add at the beginning6
4 – line numbering filter
$ nl -s "text to add at the beginning" file3.txt | cut -c7- > file4.txt $ cat file4.txt text to add at the beginningtext to add at the beginningtext to add at the beginningtext to add at the beginning1 text to add at the beginningtext to add at the beginningtext to add at the beginningtext to add at the beginning2 text to add at the beginningtext to add at the beginningtext to add at the beginningtext to add at the beginning3 text to add at the beginningtext to add at the beginningtext to add at the beginningtext to add at the beginning4 text to add at the beginningtext to add at the beginningtext to add at the beginningtext to add at the beginning5 text to add at the beginningtext to add at the beginningtext to add at the beginningtext to add at the beginning6
See you soon
Gg1