且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在awk中的反斜杠("\")定界符上分割字符串?

更新时间:2023-11-15 16:52:58

样本数据和输出是我对您要求的***猜测

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
     }'

输出

b

回想一下split返回它发现要拆分的字段数.您可以取消注释调试行,然后将看到返回值3.

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.

还请注意,对于我的测试,我必须使用2个'\'字符来处理1个字符.我认为您不需要在文件中使用它,但是如果这不适用于文件,请尝试根据需要在数据中添加额外的"\".我尝试了几种使用'\'的变体,这似乎是最简单的.欢迎其他人发表评论!

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!

我希望这会有所帮助.