In Bash, how do I add a string after each line in a file?
How do I add a string after each line in a file using bash? 开发者_Go百科Can it be done using the sed command, if so how?
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
I prefer using awk
.
If there is only one column, use $0
, else replace it with the last column.
One way,
awk '{print $0, "string to append after each line"}' file > new_file
or this,
awk '$0=$0"string to append after each line"' file > new_file
I prefer echo
. using pure bash:
cat file | while read line; do echo ${line}$string; done
If you have it, the lam (laminate) utility can do it, for example:
$ lam filename -s "string after each line"
Pure POSIX shell and
sponge
:suffix=foobar while read l ; do printf '%s\n' "$l" "${suffix}" ; done < file | sponge file
xargs
andprintf
:suffix=foobar xargs -L 1 printf "%s${suffix}\n" < file | sponge file
Using
join
:suffix=foobar join file file -e "${suffix}" -o 1.1,2.99999 | sponge file
Shell tools using
paste
,yes
,head
&wc
:suffix=foobar paste file <(yes "${suffix}" | head -$(wc -l < file) ) | sponge file
Note that
paste
inserts a Tab char before$suffix
.
Of course sponge
can be replaced with a temp file, afterwards mv
'd over the original filename, as with some other answers...
This is just to add on using the echo command to add a string at the end of each line in a file:
cat input-file | while read line; do echo ${line}"string to add" >> output-file; done
Adding >> directs the changes we've made to the output file.
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
精彩评论