Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a string at the beginning of each line in a file

Tags:

file

unix

I want to add a specific string at the beginning of each line in a file. So, if I have the below two lines in someFile.txt and want to add a date string 03/06/2012 with pipe-

Hello|there|john
Hello|there|joel

I would have-

03/06/2012|Hello|there|john
03/06/2012|Hello|there|joel

What would be the most efficient way to achieve this?

like image 528
Sajal Dutta Avatar asked Mar 06 '12 17:03

Sajal Dutta


People also ask

How do you add a line at the beginning of a file in Unix?

Use sed 's insert ( i ) option which will insert the text in the preceding line.


3 Answers

$ awk '{print "03/06/2012|" $0;}' input.txt > output.txt

Takes about 0.8 seconds for a file with 1.3M lines on some average 2010 hardware.

like image 168
miku Avatar answered Oct 08 '22 10:10

miku


sed -i 's/^/03\/06\/2012|/' input.txt
like image 23
SNathan Avatar answered Oct 08 '22 09:10

SNathan


Perl solution:

perl -ne 'print "03/06/2012|$_"' input.txt > output.txt

Just for fun, I benchmarked 10 runs in /tmp:

             Rate        awk perl_5.6.1        sed  perl_5.22  perl_5.20
awk        2.08/s         --       -10%       -10%       -26%       -32%
perl_5.6.1 2.32/s        11%         --        -0%       -17%       -24%
sed        2.33/s        12%         0%         --       -17%       -24%
perl_5.20  3.06/s        47%        32%        31%         9%         --

Tested using a 1.3M line input file created here:
perl -le 'while (1){exit if ++$n > 1300000; print $n}' > input.txt

like image 31
Chris Koknat Avatar answered Oct 08 '22 11:10

Chris Koknat