tags:

views:

44

answers:

4

is there any shell command to insert a string of characters in every line of a file.. < in the beginning or the end of every line >

+5  A: 

Lots of them.

This will work:

sed -i -e 's/.*/START & END/' file
profjim
Thanks , it worked.. Will I be able to insert line number specific variable in every line < like in line i , can i insert i-1 >
trinity
You can print the current line number in sed with the '=' command, though it is followed by a \n and I don't recall atm how to get rid of that (short of filtering everything through a second sed, which is ugly). I'll post another answer which tells you how to do what you're asking.
profjim
+3  A: 
sed -i 's/^/Before/' file.txt
sed -i 's/$/After/'  file.txt
John Kugelman
This will also work (though results go to stdout rather than to a file).
profjim
@profjim, no: the `-i` flag is present. Note that the `-e` flag is optional if there's only one script block to execute.
glenn jackman
Indeed it is, I must have misread the -i as -e.
profjim
A: 
linecount=0
while IFS= read -r LINE; do
  echo "$((linecount++)) START $LINE END"
done < file

If you want to do fancier manipulation of the linecount:

linecount=0
while IFS= read -r LINE; do
  let linecount++
  echo "$((linecount-5)) START $LINE END"
done < file
profjim
A: 

awk

awk '{print NR"START"$0"END"}' file
ghostdog74