Add text at the end of each line

I'm on Linux command line and I have file with

127.0.0.1
128.0.0.0
121.121.33.111

I want

127.0.0.1:80
128.0.0.0:80
121.121.33.111:80

I remember my colleagues were using sed for that, but after reading sed manual still not clear how to do it on command line?


Solution 1:

You could try using something like:

sed -n 's/$/:80/' ips.txt > new-ips.txt

Provided that your file format is just as you have described in your question.

The s/// substitution command matches (finds) the end of each line in your file (using the $ character) and then appends (replaces) the :80 to the end of each line. The ips.txt file is your input file... and new-ips.txt is your newly-created file (the final result of your changes.)


Also, if you have a list of IP numbers that happen to have port numbers attached already, (as noted by Vlad and as given by aragaer,) you could try using something like:

sed '/:[0-9]*$/ ! s/$/:80/' ips.txt > new-ips.txt

So, for example, if your input file looked something like this (note the :80):

127.0.0.1
128.0.0.0:80
121.121.33.111

The final result would look something like this:

127.0.0.1:80
128.0.0.0:80
121.121.33.111:80

Solution 2:

Concise version of the sed command:

sed -i s/$/:80/ file.txt

Explanation:

  • sed stream editor
  • -i in-place (edit file in place)
  • s substitution command
  • /replacement_from_reg_exp/replacement_to_text/ statement
  • $ matches the end of line (replacement_from_reg_exp)
  • :80 text you want to add at the end of every line (replacement_to_text)
  • file.txt the file name

How can this be achieved without modifying the original file?

If you want to leave the original file unchanged and have the results in another file, then give up -i option and add the redirection (>) to another file:

sed s/$/:80/ file.txt > another_file.txt

Solution 3:

sed 's/.*/&:80/'  abcd.txt >abcde.txt