简体   繁体   English

awk 用于与多个分隔符进行字符串比较

[英]awk for string comparison with multiple delimiters

I have a file with multiple delimiters, I m looking to compare the value after the first / when read from right left with another file.我有一个带有多个分隔符的文件,我希望将第一个/之后的值与另一个文件进行比较。

code :-代码 :-

awk -F'[/|]' NR==FNR{a[$3]; next} ($1 in a )' file1 file2 > output

cat file1猫文件1

AAB/BBC/customer|fed|12931|
/customer|fed|982311|
BXC/DEF/OTTA|fed|92374|
AVD/customer|FST|8736481|
FFS/T6TT/BOSTON|money|18922|
GTS/trust/YYYY|opt|62376|
XXY/IJSH/trust|opt|62376|

cat file2猫文件2

customer
trust

expected output :-预期输出:-

AAB/BBC/customer|fed|12931|
/customer|fed|12931|
AVD/customer|FST|8736481|
XXY/IJSH/trust|opt|62376|
$ awk -F\| '            # just use one FS
NR==FNR {
    a[$1]
    next
}
{
    n=split($1,t,/\//)  # ... and use split to the 1st field
    if(t[n] in a)       # and compare the last split part
        print
}' file2 file1

Output:输出:

AAB/BBC/customer|fed|12931|
/customer|fed|982311|
AVD/customer|FST|8736481|
XXY/IJSH/trust|opt|62376|

If you use this [/|] you will have 2 delimiters and you will not know what the value after the last pipe was.如果你使用这个[/|]你将有 2 个分隔符,你将不知道最后一个管道之后的值是什么。

Reading your question, you want to compare the first value after the last slash without pipe chars.阅读您的问题,您想比较没有管道字符的最后一个斜杠之后的第一个值。

If there has to be a / present in the string, you can set that as the field separator and check if there are at least 2 fields using NF > 1如果字符串中必须有/ ,您可以将其设置为字段分隔符并使用NF > 1检查是否至少有 2 个字段

Then take the last field using $NF , split on |然后使用$NF获取最后一个字段,拆分| and check if the first part is present in one of the values of file2 which are stored in array a并检查第一部分是否存在于存储在数组a中的file2的一个值中

$cat file1

AAB/BBC/customer|fed|12931|
/customer|fed|982311|
BXC/DEF/OTTA|fed|92374|
AVD/customer|FST|8736481|
FFS/T6TT/BOSTON|money|18922|
GTS/trust/YYYY|opt|62376|
XXY/IJSH/trust|opt|62376|
customer

Example code示例代码

awk -F/ '
NR==FNR {a[$1];next}
NF > 1 {
  split($NF, t, "|")
  if(t[1] in a) print
}
' file2 file1

Output输出

AAB/BBC/customer|fed|12931|
/customer|fed|982311|
AVD/customer|FST|8736481|
XXY/IJSH/trust|opt|62376|

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

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