简体   繁体   English

AWK:现场分离器为双管道或更多

[英]AWK : Field Separator as Double Pipes or more

My data: 我的资料:

-1||"A|AA"||aaa@ymail
-10||"B ||B|ttB||b|| bb@ymail
-7||C||c

I want to exchange the double pipe delimiters || 我想交换双管道定界符|| with a comma , like this: 用逗号表示,如下所示:

awk -F'||' -v OFS="," '{$1=$1} 1' 2.txt

but the output remains the same. 但输出保持不变。 The reverse case (comma delimiter to double pipe), however, works: 相反的情况(逗号分隔符为双竖线)有效:

awk -F"," -v OFS="||" '{$1=$1} 1' 1.txt

What am I doing wrong? 我究竟做错了什么?

您需要转义管道符号:

awk -F '[|][|]' -v OFS="," '{$1=$1}1'

You need to escape metacharacters like | 您需要转义|元字符 or use them in character class so that they are considered literals. 或在字符类中使用它们,以便将它们视为文字。 They are considered logical OR notation without escapes. 它们被认为是逻辑OR符号,不能转义。 Try this: 尝试这个:

$ awk -F'[|][|]' -v OFS="," '{$1=$1} 1' data
-1,"A|AA",aaa@ymail
-10,"B ,B|ttB,b, bb@ymail
-7,C,c

Different ways to do this : 不同的方式来做到这一点:

awk -F '[|][|]' -v OFS="," '{$1=$1}1' # as suggested by accepted anwer
awk -F '[|]{2}' # my favorite as it is easier to extend this solution to more than two pipes
awk -F '\\|\\|' -v OFS="," '{$1=$1}1' # another way to escape
awk -F "\\\|\\\|" -v OFS="," '{$1=$1}1' # see https://superuser.com/a/1249834

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

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