SED/AWK – Add to the End or Beginning of a Line

From time to time it is required to modify some file very fast.

And it goes without saying that the most popular command line tools for this in Linux are sed and awk – the two best text processing programs.

In the following article, you’ll find an information about how to add some text, character or comma to the beginning or to the end of every line in a file using sed and awk.

Also you will learn how to turn multiple lines of a file into one comma-separated line.

SED/AWK – Add to the Beginning

Use the below commands to append some PREFIX (some text or character) to the beginning of every line in a FILE:

$ awk '{print "PREFIX"$0}' FILE

– or –

$ sed 's/^/PREFIX/' FILE

Cool Tip: Do not be a bore! Add COLORS to your Bash script! Make it look AWESOME! Read more →

SED/AWK – Add to the End

Use the following commands to append some SUFFIX (some text or character) to the end of every line in a FILE:

$ awk '{print $0"SUFFIX"}' FILE

– or –

sed 's/$/SUFFIX/' FILE

SED/AWK – Add to the Beginning and End

Use the following commands to append some PREFIX to the beginning and some SUFFIX to the end of every line in a FILE:

$ awk '{print "PREFIX"$0"SUFFIX"}' FILE

– or –

$ sed "s/.*/PREFIX&SUFFIX/" FILE

Cool Tip: You can also easily remove characters from the beginning or from the end of a line using cut command! Read more →

Multiple Lines into One Comma-Separated

Let’s say you have some file with multiple lines.

And you need to turn these multiple lines into one comma-separated line.

There are many ways how it can be achieved, but i often use one of the following one-liners.

Use one of these commands to append commas to the end of every line in a file, except the last one, and turn the multiple lines into one comma-separated line:

$ echo $(awk 'NR > 1{print line", "}{line=$0;}END{print $0" "}' FILE)

– or –

$ paste -d, -s FILE

Example:

$ cat file.txt
I Love Bash
I Love Bash
I Love Bash

$ echo $(awk 'NR > 1{print line", "}{line=$0;}END{print $0" "}' file.txt)
I Love Bash, I Love Bash, I Love Bash

$ paste -d, -s file.txt
I Love Bash,I Love Bash,I Love Bash