在awk中使用多个字符串作为分隔符 [英] Using multiple character string as separator in awk
问题描述
我有一个文本文件,其中的记录具有以下格式:
I have a text file in which records are of the following format:
A || o || BCD || o || E || o || XYZ
A||o||BCD||o||E||o||XYZ
我要使用'|| o ||'作为获取我的记录的分隔符:
I want to use '||o||' as the separator to get my records:
但是当我使用时:
awk -F'||o||' '{print $1}'
我遇到以下错误:
awk:正则表达式中的非法主语|| o ||在| o ||
awk: illegal primary in regular expression ||o|| at |o||
任何帮助将不胜感激.
推荐答案
您需要使用正则表达式对文字管道进行转义
you need to escape literal pipes in a regular expression
awk -F'[|][|]o[|][|]' '{print $1}'
或
awk -F'[|]{2,2}o[|]{2,2}' '{print $1}'
通常的反斜杠转义在awk中是不同的,因此要使用它(至少在GNU bash版本4.3.42上)
The usual backslash escape is different in awk, so to use it (at least on GNU bash, version 4.3.42)
awk 'BEGIN{FS="\\|\\|o\\|\\|"} {print $1}' pipe.txt
以及使用-F
选项的这种丑陋语法
and also this ugly syntax using the -F
option
awk -F "\\\|\\\|o\\\|\\\|" '{print $1}' pipe.txt
在此处对此进行了详细解释.
The double escapes are well explained here.
这篇关于在awk中使用多个字符串作为分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!