Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a prefix string to beginning of each line

I have a file as below:

line1 line2 line3 

And I want to get:

prefixline1 prefixline2 prefixline3 

I could write a Ruby script, but it is better if I do not need to.

prefix will contain /. It is a path, /opt/workdir/ for example.

like image 844
pierrotlefou Avatar asked Jan 20 '10 06:01

pierrotlefou


People also ask

How do you add a string at the beginning of each line in Linux?

The ^ character is what instructs the sed command to add a character to the beginning of each line. Here's the syntax for adding a space to the beginning of each line using sed . Alternatively, use the -i option with the sed command to edit a file in place.

How do you add a string at the end of each line in Unix?

† By default xargs will pass multiple lines of input to a single command, appending them all to its argument list. But specifying -I % makes xargs put the input at the specified place in the command, and only put one line there at a time, running echo as many times as required.


2 Answers

# If you want to edit the file in-place sed -i -e 's/^/prefix/' file  # If you want to create a new file sed -e 's/^/prefix/' file > file.new 

If prefix contains /, you can use any other character not in prefix, or escape the /, so the sed command becomes

's#^#/opt/workdir#' # or 's/^/\/opt\/workdir/' 
like image 73
Alok Singhal Avatar answered Sep 28 '22 07:09

Alok Singhal


awk '$0="prefix"$0' file > new_file 

In awk the default action is '{print $0}' (i.e. print the whole line), so the above is equivalent to:

awk '{print "prefix"$0}' file > new_file 

With Perl (in place replacement):

perl -pi 's/^/prefix/' file 
like image 33
Vijay Avatar answered Sep 28 '22 05:09

Vijay