In Bash, how do I add a string after each line in a file?

LinuxBashUnixSed

Linux Problem Overview


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?

Linux Solutions


Solution 1 - Linux

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

Solution 2 - Linux

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

Solution 3 - Linux

I prefer echo. using pure bash:

cat file | while read line; do echo ${line}$string; done

Solution 4 - Linux

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

$ lam filename -s "string after each line"

Solution 5 - Linux

  1. Pure POSIX shell and sponge:

    suffix=foobar
    while read l ; do printf '%s\n' "$l" "${suffix}" ; done < file | 
    sponge file
    
  2. xargs and printf:

    suffix=foobar
    xargs -L 1 printf "%s${suffix}\n" < file | sponge file
    
  3. Using join:

    suffix=foobar
    join file file -e "${suffix}" -o 1.1,2.99999 | sponge file
    
  4. 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...

Solution 6 - Linux

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.

Solution 7 - Linux

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJason VolkozView Question on Stackoverflow
Solution 1 - LinuxTom DeGisiView Answer on Stackoverflow
Solution 2 - LinuxOptimus PrimeView Answer on Stackoverflow
Solution 3 - Linux欢乐的XiaoxView Answer on Stackoverflow
Solution 4 - Linuxmartin claytonView Answer on Stackoverflow
Solution 5 - LinuxagcView Answer on Stackoverflow
Solution 6 - LinuxSynt4x 4rr0rView Answer on Stackoverflow
Solution 7 - LinuxhendryView Answer on Stackoverflow