从第二个字段逐行搜索模式并打印出与找到模式的行对应的第一个字段

search for pattern line by line from the second field and print out the first field corresponding to the line where the pattern was found

我下面有以下 0.txt 文件,按列(字段)分隔内容:

'Disinfectants', 'Brand A', 'Brand B', 'Brand C'
'brand A', 'below brand C', 'greater than brand B'
'brand B', 'greater than brand D', 'below brand A'

我想在每次出现模式(比如“品牌 A”)时(从第二列开始)查找,并打印出属于找到该模式的行的第一列的内容。 结果文件的内容如下:

Disinfectants
brand B

我见过其他类似的问题,但只打印发现模式的列本身,通常使用 grep

编辑更新:来自@jubilatious1 建议 ,我在 OS 上发现了一个问题 () 作为我寻找解决方案的一部分。

awk '/brand A/{ print substr( , RLENGTH )}' 0.txt > 1.txt

但我的 1.txt 输出与预期不同,因为它只打印了第一个字段(列)的部分内容:

'brand
'brand

此外,仅使用 awk '/brand A/{ print substr( , RLENGTH )}' 我无法指定搜索仅适用于每一行的第二个字段(列)。

编辑更新 1:也许只是修复 awk '/brand A/{ print substr( , RLENGTH )}' 的输出,以便正确打印第一列中字段的内容是第一步。

Hackish 管道:

cut -d, -f2- 0.txt | grep -ni 'brand a' | sed 's/:.*/p/' | sed -nf- 0.txt | cut -d, -f1

  • 以逗号分隔并省略字段 1
  • grep for line numbers with 'brand a'(不区分大小写)
  • 将行号转换为 {linenumber}p -- 打印该行的 sed 命令
  • 将这些 sed 命令通过管道传输到 sed -nf- ...这只会在标准输入指示时打印...所以您只会得到您想要的行
  • 以逗号分隔并仅打印第一个字段

或 perl:

perl -lanF, -e 'print $F[0] if grep /brand a/i, @F[1..$#F]' 0.txt

  • 在逗号上自动拆分为 @F,如果在任何其他字段中发现 'brand a'(不区分大小写),则打印第一个字段。

两者都输出:

'Disinfectants'
'brand B'

您可以随意去除单引号,或者,您可以更改 split perl 自动拆分的正则表达式:

perl -lanF"/[',]+/" -e 'print $F[1] if grep /brand a/i, @F[2..$#F]' brand.txt

得到这个:

Disinfectants
brand B

...请注意,一旦该行以分隔符开始,$F[0] 就是一个空字符串。