Add a prefix string to beginning of each line

pierrotlefou picture pierrotlefou · Jan 20, 2010 · Viewed 384.8k times · Source

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.

Answer

Alok Singhal picture Alok Singhal · Jan 20, 2010
# 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/'