CLI tip 4: serialize file contents to a single line
The -s
option is one of the useful, but lesser known feature of the paste
command. It helps you to serialize input file contents to a single output line.
$ cat colors.txt
blue
white
orange
$ paste -sd, colors.txt
blue,white,orange
If multiple files are passed, serialization of each file is displayed on separate output lines.
$ paste -sd: <(seq 3) <(seq 5 9)
1:2:3
5:6:7:8:9
The advantage of using paste
instead of other options like tr
, awk
, etc is that you do not have to worry about trailing delimiters, newlines, etc. For example:
# issue 1: trailing comma
# issue 2: no newline at the end
$ <colors.txt tr '\n' ','
blue,white,orange,
# correcting the above two issues
$ <colors.txt tr '\n' ',' | sed 's/,$/\n/'
blue,white,orange
Here's an equivalent awk
solution for single file input. While slower and complicated compared to the paste
solution, you get more flexibility since awk
is a programming language. For example, it is pretty easy to use multicharacter output delimiter.
$ awk -v ORS= 'NR>1{print ","} 1; END{print "\n"}' colors.txt
blue,white,orange
$ awk -v ORS= 'NR>1{print " : "} 1; END{print "\n"}' colors.txt
blue : white : orange
Video demo:
See paste command chapter from my Command line text processing with GNU Coreutils ebook for more details.
See my GNU awk one-liners ebook if you are interested in learning about the awk
command.