Friday, April 19, 2013

Replace end of lines (\n) by any character

Just found out a classic UNIX command I never used before.

The command "paste" allows you to replace end of lines (i.e \n) by any character of your choice.

I normally used sed for this purpose but the syntax is quite...dirty. For example to replace all end of lines by a space with sed, the command is :
 $ sed ':a;N;$!ba;s/\n/ /g' /path/to/file  

With paste the syntax is much more human readable :
 $ paste -s /path/to/file  

By default "paste" replaces end of lines with tabs, to specify a delimiter use the -d option.

Replace end of lines with spaces :
 $ paste -s -d' ' /path/to/file  

Replace end of lines with commas :
 $ paste -s -d',' /path/to/file  

 Use '-' for reading from stdin :
 echo -e "a\nb\nc\nd" | paste -s -d',' -  
 a,b,c,d  

More info in the man as always.

This tips will not change your life but i found it quite useful !

Hope that helps !

No comments:

Post a Comment