tags:

views:

264

answers:

3

How do I add a string after each line in a file using bash? Can it be done using the sed command, if so how?

+1  A: 

If your sed allows in place editing via the -i parameter:

sed -e 's/$/string after each line/' -i filename

If not, you have to make a temporary file:

typeset TMP_FILE=$( mktemp )

touch "${TMP_FILE}"
cp -p filename "${TMP_FILE}"
sed -e 's/$/string after each line/' "${TMP_FILE}" > filename

Yours,
Tom

Tom DeGisi
Thanks, it worked!
Jason Volkoz
Why do you `touch` the temporary file? And I would make the `sed` command conditional on the success of the `cp` or the original could be lost.
Dennis Williamson
I touched the file to quickly reserve the temporary name. This may not be needed. I think you are right about making the sed command conditional on the success of the cp. Why not edit the code to make that fix. I won't mind a bit!Yours,Tom
Tom DeGisi
A: 

Sed is a little ugly, you could do it elegantly like so:

hendry@i7 tmp$ cat foo 
bar
candy
car
hendry@i7 tmp$ for i in `cat foo`; do echo ${i}bar; done
barbar
candybar
carbar
hendry
Fails for files with more lines than the shell's maximum argument limit.Try:cat foo | while read a ; do echo ${a}bar ; doneor something like that instead; it's a suitable replacement for for in in most cases.
alex
It also fails for lines with spaces in them.
Dennis Williamson
Er, no it doesn't fail Dennis.shell's maximum argument limit? Crikey you are being pendantic.
hendry
Yes it does:$ cat foofoo barbazalex@armitage:~$ for i in `cat foo`; do echo ${i}bar; donefoobarbarbarbazbarbut after some tests, I might be wrong about my reasoning, but Dennis is right
alex
foo in my case is a file. You would not get problems with spaces and it would just iterate on line endings in the file.
hendry
A: 

If you have it, the lam (laminate) utility can do it, for example:

$ lam filename -s "string after each line"
martin clayton