Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add prefix to every line in text in bash

Tags:

text

bash

awk

Suppose there is a text file a.txt e.g.

aaa
bbb
ccc
ddd

I need to add a prefix (e.g. myprefix_) to every line in the file:

myprefix_aaa
myprefix_bbb
myprefix_ccc
myprefix_ddd

I can do that with awk:

awk '{print "myprefix_" $0}' a.txt 

Now I wonder if there is another way to do that in shell.

like image 380
Michael Avatar asked Nov 07 '13 09:11

Michael


2 Answers

With sed:

$ sed 's/^/myprefix_/' a.txt
myprefix_aaa
myprefix_bbb
myprefix_ccc
myprefix_ddd

This replaces every line beginning ^ with myprefix_. Note that ^ is not lost, so this allows to add content to the beginning of each line.

You can make your awk's version shorter with:

$ awk '$0="myprefix_"$0' a.txt
myprefix_aaa
myprefix_bbb
myprefix_ccc
myprefix_ddd

or passing the value:

$ prefix="myprefix_"
$ awk -v prefix="$prefix" '$0=prefix$0' a.txt
myprefix_aaa
myprefix_bbb
myprefix_ccc
myprefix_ddd

It can also be done with nl:

$ nl -s "prefix_" a.txt | cut -c7-
prefix_aaa
prefix_bbb
prefix_ccc
prefix_ddd

Finally: as John Zwinck explains, you can also do:

paste -d'' <(yes prefix_) a.txt | head -n $(wc -l a.txt)

on OS X:

paste -d '\0' <(yes prefix_) a.txt | head -n $(wc -l < a.txt)
like image 192
fedorqui 'SO stop harming' Avatar answered Oct 16 '22 07:10

fedorqui 'SO stop harming'


Pure bash:

while read line
do
    echo "prefix_$line"
done < a.txt
like image 26
John Zwinck Avatar answered Oct 16 '22 07:10

John Zwinck