Linux append text to end of line

Bash shell user here. I need to append text to end of line not end of file. I know how to append text to end of file on Linux using:

echo 'data' >> my.txt

I have line as follows:

this is a line

I want it to be like as follows:

this is a line *NEWTEXT*

How do I append text to end of line stored in a file?

Try sed or awk to append text to end of line. Tested with GNU/Linux version of sed and awk but should work with on any Unix-like systems:

sed 's/$/ TEXT/' <<<"This is a test"

OR

awk '{print $0, "TEXT"}' <<<"This is a test"

Here is output:

This is a test TEXT

nixcraft recommended awk and sed, which are both clean and accurate. However, I am not sure if you meant to say that you wanted to append something to “every line” in the existing text file? If so, then I would use sed (stream editor) to get there:

root#  echo "this is a line" > my.txt
root#  cat my.txt
this is a line
root#  cat my.txt | sed 's/$/ \*NEWTEXT\*/' > mynewfile.txt
root#  cat mynewfile.txt
this is a line *NEWTEXT*
root#

Tools like grep, sed and awk can also pattern match, and swap in/out information easily.

One of my favorite actions is to strip out blank lines and comments from configuration files, so I can see what’s active.

   cat config.txt | grep -v ^$ |grep -v "^#" | more

The first grep “ignores” blank lines, while the second ignores leading # symbols.
If you wanted to convert empty lines to comment markers, then sed would be great at that:

cat config.txt | sed 's/^$/# /' > revised_config.txt
1 Like

Nice addition.

Assuming using gnu/sed, one can combine everything in a single line

sed -i 's/$/ \*NEWTEXT\*/' my.txt