简体   繁体   English

如何将awk分隔符设置为字符串或字符?

[英]How can I set awk delimiter to either string or character?

How to use a string and another character as simultaneous delimiters in awk? 如何在awk中使用string和另一个character作为同时分隔符?

sdlcb@ubuntu:~/AMD_C/SO$ echo "111:222text333:444" | awk -F ':' '{print $2}'
222text333

sdlcb@ubuntu:~/AMD_C/SO$ echo "111:222text333:444" | awk -F "text" '{print $2}'
333:444

So the question is, how can we use " text " and " : " as delimiters at the same time, so that {print $2} will print 222 as output? 所以问题是,我们如何同时使用“ text ”和“ : ”作为分隔符,以便{print $2}将打印222作为输出? Consider input as in the examples above. 考虑上面示例中的输入。

You can use simple alternation 您可以使用简单的替换

$ echo "111:222text333:444" | awk -F "text|:" '{print $2}'
222

What it does 它能做什么

  • -F "text|:" sets the field seperator as text or : -F "text|:"将字段分隔符设置为text:

Test 测试

To ensure that this correctly delimits the fields 确保正确分隔字段

$echo "111:222text333:444" | awk -F "text|:" '{print $1,$2,$3,$4}'
111 222 333 444

EDIT 编辑

If you want to use | 如果你想使用| as delimitter, escape the | 作为分隔符,逃避| as

$ echo "111:222text333:444|hello" | awk -F '\\||text|:' '{print $1,$2,$3,$4,$5}'
111 222 333 444 hello

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM