Thursday, July 14, 2016

How to substitute newline with one or multiple characters using tr, sed or awk

If you have a file

cat file.txt 
one
two
three
four
five

and want to substitute every new line with one character, (eg. ;) you can use tr

tr '\n' ';' < file.txt
one;two;three;four;five;

If you want to substitute every new line with multiple characters (eg. :::), you cannot use tr, in this case in bash it would be better to use sed

sed ':a;N;$!ba;s/\n/:::/g' file.txt
one:::two:::three:::four:::five

Or using awk and defining output record separator ORS:

awk 1 ORS=':::' file.txt
one:::two:::three:::four:::five:::

No comments:

Post a Comment