In Bash, how do I add a string after each line in a file?
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...