Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add text at the end of each line in unix

Tags:

shell

unix

ksh

awk

I am doing certain text processing operations and finally able to get a file something like this

india sudan japan france 

now I want to add a comment in the above file like in the final file it should be something like

india | COUNTRY sudan | COUNTRY japan | COUNTRY france | COUNTRY 

like a same comment across the whole file. How do I do this?

like image 220
user2647888 Avatar asked Apr 15 '14 08:04

user2647888


People also ask

How do you add a string at the end of each line in Unix?

† By default xargs will pass multiple lines of input to a single command, appending them all to its argument list. But specifying -I % makes xargs put the input at the specified place in the command, and only put one line there at a time, running echo as many times as required.

How do you add a string at the end of a file in Unix?

You need to use the >> to append text to end of file. It is also useful to redirect and append/add line to end of file on Linux or Unix-like system.

How do you add a string at the beginning of each line in Unix?

The ^ character is what instructs the sed command to add a character to the beginning of each line. Here's the syntax for adding a space to the beginning of each line using sed . Alternatively, use the -i option with the sed command to edit a file in place.


1 Answers

There are many ways:

sed: replace $ (end of line) with the given text.

$ sed 's/$/ | COUNTRY/' file india | COUNTRY sudan | COUNTRY japan | COUNTRY france | COUNTRY 

awk: print the line plus the given text.

$ awk '{print $0, "| COUNTRY"}' file india | COUNTRY sudan | COUNTRY japan | COUNTRY france | COUNTRY 

Finally, in pure bash: read line by line and print it together with the given text. Note this is discouraged as explained in Why is using a shell loop to process text considered bad practice?

$ while IFS= read -r line; do echo "$line | COUNTRY"; done < file india | COUNTRY sudan | COUNTRY japan | COUNTRY france | COUNTRY 
like image 152
fedorqui 'SO stop harming' Avatar answered Sep 30 '22 10:09

fedorqui 'SO stop harming'