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
2010-05-19 21:54:58
Thanks, it worked!
Jason Volkoz
2010-05-19 22:03:25
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
2010-05-20 00:19:41
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
2010-05-20 00:50:31
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
2010-05-19 21:57:51
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
2010-05-19 22:36:46
Er, no it doesn't fail Dennis.shell's maximum argument limit? Crikey you are being pendantic.
hendry
2010-05-20 10:16:39
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
2010-05-20 21:36:05
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
2010-05-24 09:33:54
A:
If you have it, the lam (laminate) utility can do it, for example:
$ lam filename -s "string after each line"
martin clayton
2010-05-19 22:07:16