I have file like below
abc 12 34 45 code
abcdef 451 1 4 code
ghtyggg 4 56 3 code
I need to change this to
abc|12|34|45|code|
abcdef|451|1|4|code|
ghtyggg|4|56|3|code|
I tried replace space with | in sed ... but in the middle some row has tab... and it is replace all space with pipe meaning
abcdef |||451||1|4||code
Here's the correct way:
$ sed "s/ *$//; s/[[:space:]]\+/|/g; s/$/|/" file
abc|12|34|45|code|
abcdef|451|1|4|code|
ghtyggg|4|56|3|code|
it is not working.. it is just appening | in the end
aaaaaaaaaaaaaaaaaaaaaar 1 0 4 alpha
bbbbbbbbbbbbbbbbbbbbbbbbbbbbh 2 4 2 number
cccccccccccccccccccccr 3 6 19 alpha
ddddddddddddddde 4 27 2 number
after running
aaaaaaaaaaaaaaaaaaaaaar 1 0 4 alpha|
bbbbbbbbbbbbbbbbbbbbbbbbbbbbh 2 4 2 number|
cccccccccccccccccccccr 3 6 19 alpha|
ddddddddddddddde 4 27 2 number|
I think the space r tab is changing while i am pasting here...
Works fine here.
$ uname
Linux
Maybe your sed does not understand [[:space:]] syntax. Try this:
$ tr "\t" " " < file | sed "s/ *$//; s/ \+/|/g; s/$/|/"
aaaaaaaaaaaaaaaaaaaaaar|1|0|4|alpha|
bbbbbbbbbbbbbbbbbbbbbbbbbbbbh|2|4|2|number|
cccccccccccccccccccccr|3|6|19|alpha|
ddddddddddddddde|4|27|2|number|
$ awk '$1=$1' OFS="|" file | sed 's/$/|/'
aaaaaaaaaaaaaaaaaaaaaar|1|0|4|alpha|
bbbbbbbbbbbbbbbbbbbbbbbbbbbbh|2|4|2|number|
cccccccccccccccccccccr|3|6|19|alpha|
ddddddddddddddde|4|27|2|number|
Yes, misread something... in that case:
awk 'NF=NF+1' OFS="|" file
1 Like
How about this one? simple and easy to understand
cat a1.dat|tr -s ' ' '|'| sed 's/$/|/'
abc|12|34|45|code|
abcdef|451|1|4|code|
ghtyggg|4|56|3|code|