views:

146

answers:

3

Hi,

I have a file below :

line1
line2
line3

And I want to get

prefixline1
prefixline2
prefixline3

I could write a ruby script but it is better if I don't need to.

EDIT: prefix will contains / , it is a path , /opt/workdir/ for example.

+8  A: 
sed -e 's/^/prefix/' file

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/'.

Alok
What if the prefix contains the `/` for example `/opt/path`
pierr
You can use any character in place of `/` for the `s` command.
Alok
if prefix contains `/` then its more easy to use `awk`.
Vijay Sarathi
@benjamin, I had already upvoted your answer, however, I prefer `sed` for lightweight tasks such as this. If "prefix" is known, it's very easy to pick a character not from "prefix".
Alok
I am upvoting ur comment:).
Vijay Sarathi
Thanks for pointing out sed -i; I wasn't aware of the in-place edit capability.
toolic
+2  A: 
awk '{print "prefix"$0}' file > new_file
Vijay Sarathi
A: 

using the shell

#!/bin/bash
prefix="something"
file="file"
while read -r line
do
 echo "${prefix}$line"
done <$file > newfile
mv newfile $file
ghostdog74