How to insert a different delimiter in between two

2019-07-13 10:31发布

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.

标签: shell sed awk
4条回答
forever°为你锁心
2楼-- · 2019-07-13 11:05

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.

查看更多
一夜七次
3楼-- · 2019-07-13 11:05

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.

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-07-13 11:11
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|
查看更多
叛逆
5楼-- · 2019-07-13 11:13

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
查看更多
登录 后发表回答