AWK:字段分隔符为双管或更多

时间:2014-03-28 11:45:14

标签: unix awk

我的数据:

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

我想用逗号||交换双管分隔符,,如下所示:

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

但输出保持不变。 但是,相反的情况(双管道的逗号分隔符)有效:

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

我做错了什么?

3 个答案:

答案 0 :(得分:9)

您需要转义管道符号:

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

答案 1 :(得分:4)

您需要转义像|这样的元字符,或者在字符类中使用它们,以便将它们视为文字。它们被认为是没有转义的逻辑OR符号。试试这个:

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

答案 2 :(得分:1)

执行此操作的不同方法:

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