3

This is my input file.

3400,2
3400,27
3400,DC
3400,TF
5600,KA
5600,KN
5600,TF
0313,EX
0313,EY
0313,EZ
0313,FD
0313,FE
0313,JB
0313,JC
0313,KG
0313,T8

I want my output to be

400,2\|3400,27\|3400,DC\|3400,TF\|5600,KA\|5600,KN\|5600,TF\|0313,EX\|0313,EY\|0313,EZ\|0313,FD\|0313,FE\|0313,JB\|0313,JC\|0313,KG\|0313,T8

I am running the code as follows:

cat f.txt | tr '\n' "\|"
3400,2|3400,27|3400,DC|3400,TF|5600,KA|5600,KN|5600,TF|0313,EX|0313,EY|0313,EZ|0313,FD|0313,FE|0313,JB|0313,JC|0313,KG|0313,T8

cat f.txt | tr '\n' "\\\|"
3400,2\3400,27\3400,DC\3400,TF\5600,KA\5600,KN\5600,TF\0313,EX\0313,EY\0313,EZ\0313,FD\0313,FE\0313,JB\0313,JC\0313,KG\0313,T8

How can I reach my expected output ?

  • You could do the following ways: perl -0777pe 's/\n(?!\z)/\\|/g' f.txt perl -pe 'eof || s/\n/\\|/' f.txt – user218374 May 6 '17 at 4:49
1

You could do this in many ways, with many tools, e.g. with awk like this:

cat f.txt | awk 'BEGIN{ORS="\\|"}1' 

@don_cristi remarked correctly, that "This will print a trailing \| and no trailing newline", so here is a version that fixes both, if that is needed for your use-case:

awk 'p{printf "%s\\|",p} {p=$0} END{print p}'
|improve this answer|||||
  • @don_crissti Good catch, I will correct my answer. – Alex Stragies May 5 '17 at 19:57

Not the answer you're looking for? Browse other questions tagged or ask your own question.