我有一个类似于在匹配之前和之后打印文本,从特定的开始到结束字符串。的问题,但有点扭曲。
我的文件是一个大型的CSV,是手动构建的。它多次包含字符串"WAP“。我的工作是检测字符串WAP的所有实例,并打印每个匹配之前的两个字符,只要该字符是一个数字。
我从来没有必要做这样的字符串搜索,因此,任何您可以提供的指导将对我的任务有很大的帮助。谢谢大家。
丹尼尔~
Sample from spreadsheet: ,x,x,x,x,x,xx,Yes,"1 WAP, other stuff, other stuff",no,x
Intended output from that line: 1
这是我所取得的成就,因为我以前从未使用过awk:
awk '/WAP/{print}‘~/电子表格/waps.csv
似乎要打印每条匹配线。我认为我需要做的是保持循环运行,将字符累加起来,直到匹配WAP,然后在更早的时候抓取字符。但上一次我这么做是在1999年上大学。
发布于 2019-06-11 20:33:42
下面是一个示例awk脚本。
awk '/..WAP../{print substr($0, index($0,"WAP") - 2, 7);}' input.csv样本输入:
junk
line 1 12WAP34 678
another line abWAPcdefg
WAP123
junk WAP产出:
12WAP34
abWAPcd说明:
/..WAP../{ # for line containt WAP with 2 chars wrap
wapPosition = index($0,"WAP") - 2; # find the position of WAP - 2 chars
output = substr($0, wapPosition, 7);# output is 7 chars length from wapPostion
print output; # print output
}发布于 2019-06-11 22:02:22
使用GNU,您可以在match函数中使用捕获组,并通过可选的数组参数访问其内容:
$ echo ',x,x,x,x,x,xx,Yes,"1 WAP, other stuff, other stuff",no,x' |
awk 'match($0,/([0-9]).WAP/,a) {print a[1]}'
1更可移植的是,您可以使用match + substr作为
awk 'match($0,/[0-9].WAP/) {print substr($0,RSTART,1)}'发布于 2019-06-12 12:20:39
假设WAP每行只能发生一次,我认为这可能是您真正想要的。给定此输入文件:
$ cat file
,x,x,x,x,x,xx,Yes,7,WAP,no,x
,x,x,x,x,x,xx,Yes,3 WAP,no,x
,x,x,x,x,x,xx,Yes,"1 WAP",no,x用GNU awk:
$ awk 'match($0,/([0-9])[^,]WAP/,a){print a[1]}' file
3
1用任何一只头巾:
$ awk 'match($0,/[0-9][^,]WAP/){print substr($0,RSTART,1)}' file
3
1https://unix.stackexchange.com/questions/524281
复制相似问题