Split string on a backslash (“\”) delimiter in awk?

萝らか妹 提交于 2020-07-30 00:55:53

问题


I am trying to split the string in a file based on some delimiter.But I am not able to achieve it correctly... Here is my code below.

awk 'var=split($2,arr,'\'); {print $var}' file1.dat

Here is my sample data guys.

Col1 Col2
abc  123\abc
abcd 123\abcd

Desire output:

Col1 Col2
abc  abc
abcd abcd

回答1:


Sample data and output is my best guess at your requirement

 echo '1:2\\a\\b:3' | awk -F: '{ 
     n=split($2,arr,"\\")
     # print "#dbg:n=" n
     var=arr[3]
     print var
     }'

output

b

Recall that split returns the number of fields that it found to split. You can uncomment the debug line and you'll see the value 3 returned.

Note also that for my test, I had to use 2 '\' chars for 1 to be processed. I don't think you'll need that in a file, but if this doesn't work with a file, then try adding extra '\' as needed to your data. I tried several variations on how to use '\', and this seems the most straightforward. Others are welcome to comment!

I hope this helps.




回答2:


You don't need to call split. Just use \\ as field separator:

echo 'a\b\c\d' | awk -F\\ '{printf("%s,%s,%s,%s\n", $1, $2, $3, $4)}'

OUTPUT:

a,b,c,d



回答3:


As some of the comments mentioned, you have nested single quotes. Switching one set to use double quotes should fix it.

awk 'var=split($2,arr,"\"); {print $var}' file1.dat

I'd prefer piping to another awk command to using split.I don't know that one is better than the other, it is just a preference.

awk '{print $2}' file1.dat | awk -F'\' '{...}'



回答4:


You need to escape the backslash you're trying to split on. You can do this in you split using double-quotes like this: "\\"

Also, you can take an array slice to make your code more readable (and avoid defining another var). This should work for you:

awk 'NR==1 { print } NR>=2 { split($0,array,"\\"); print $1,array[2] }' file1.dat

HTH




回答5:


awk '{sub(/123\\/,"")}1' file

Col1 Col2
abc  abc
abcd abcd


来源:https://stackoverflow.com/questions/10130972/split-string-on-a-backslash-delimiter-in-awk

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!