user3202415
user3202415

Reputation: 117

How to insert a different delimiter in between two columns in shell

I 've a file as below

ABc def|0|0|0| 1 | 2| 9|
0 2930|0|0|0|0| 1 | 2| 9|

Now, i want to split the first column with the same delimiter.

output:

ABc|def|0|0|0| 1 | 2| 9|
0|2930|0|0|0|0| 1 | 2| 9|

Please help me out with awk.

Upvotes: 2

Views: 2228

Answers (4)

Jotne
Jotne

Reputation: 41460

Another awk

awk '{sub(/ /,"|")}1' file
ABc|def|0|0|0| 1 | 2| 9|
0|2930|0|0|0|0| 1 | 2| 9|

Without the leading space, this works fine.

Upvotes: 1

NeronLeVelu
NeronLeVelu

Reputation: 10039

sed 's/^[[:blank:]]\{1,\}/  /;/^\([^|]\{1,\}\)[[:blank:]]\{1,\}\([^|[[:blank:]]\)/ s//\1|\2/'

assuming first column is blank for empty, a blank (or several) as the separator than another non blank or | this allow this

ABc def|0|0|0| 1 | 2| 9|
 def|0|0|0| 1 | 2| 9|
ABc|def|0|0|0| 1 | 2| 9|

Upvotes: -1

Kent
Kent

Reputation: 195289

You said you want to replace the delimiter (space->pipe) in first column.

It could happen that in your first col, there is no space, but in other columns, there are spaces. In this case, you don't want to do any change on that line. Also in your first column, there could be more spaces, I guess you want to have them all replaced. So I cannot think of a shorter way for this problem.

awk -F'|' -v OFS="|" '{gsub(/ /,"|",$1)}7' file

Upvotes: 0

fedorqui
fedorqui

Reputation: 290525

You can use sed for this:

$ sed 's/ /|/' file
ABc|def|0|0|0| 1 | 2| 9|
0|2930|0|0|0|0| 1 | 2| 9|

The way it is defined, it just replaces the first space with a |, which is exactly what you need.

With awk it is a bit longer:

$ $ awk 'BEGIN{FS=OFS="|"}{split($1, a, " "); $1=a[1]"|"a[2]}1' file
ABc|def|0|0|0| 1 | 2| 9|
0|2930|0|0|0|0| 1 | 2| 9|

After definining input and output field separator as |, it splits the first field based on space. Then prints the line back.

Upvotes: 2

Related Questions