简体   繁体   English

如何在bash中打印具有特定列匹配数组成员的行

[英]how to print lines with specific column matching members of array in bash

#!/bin/bash    
awk '$1 == "abc" {print}' file # print lines first column matching "abc"

How to print lines when the first column matching members of array("12" or "34" or "56")? 当第一列匹配array(“ 12”或“ 34”或“ 56”)的成员时,如何打印行?

#!/bin/bash
ARR=("12" "34" "56")

Add
Also, how to print lines when the first column exactly matching members of array("12" or "34" or "56")? 另外,当第一列与array的成员完全匹配时如何打印行(“ 12”或“ 34”或“ 56”)?

You could use bash to interpolate the string to a regex pattern used in Awk , by changing the IFS value to a | 通过将IFS值更改为| ,可以使用bash将字符串插入到Awk使用的正则表达式模式| character and do array expansion as below: 字符并进行数组扩展,如下所示:

ARR=("12" "34" "56")    

regex=$( IFS='|'; echo "${ARR[*]}" )
awk -v str="$regex" '$1 ~ str' file

The array expansion converts the list elements to a string delimited with | 数组扩展将列表元素转换为以|分隔的字符串 , for eg 12|34|56 in this case. ,例如在这种情况下为12|34|56

The $() runs in the sub-shell do that the value of IFS is not reflcted in the parent shell. $()在子外壳程序中运行,以确保未在父外壳程序中反映IFS的值。 You could make it in one line as 您可以将其作为一行

awk -v str="$( IFS='|'; echo "${ARR[*]}" )" '$1 ~ str' file

OP had also asked for an exact match of the strings from the array in the file, in that case using grep with its ERE support can do the job OP还要求从文件中的数组中精确匹配字符串,在这种情况下,使用带有ERE支持的grep可以胜任

regex=$( IFS='|'; echo "${ARR[*]}" )
egrep -w "$regex" file

(or) (要么)

grep -Ew "$regex" file

awk单线

awk -v var="${ARR[*]}" 'BEGIN{split(var,array," "); for(i in array) a[array[i]] } ($1 in a){print $0}' file

The following code does the trick: 以下代码可以解决问题:

awk 'BEGIN{myarray [0]="aaa";myarray [1]="bbb"; test=0 }{

test=0;
for ( x in myarray ) {
    if($1 == myarray[x]){
    test=1;
    break;
    }

}
if(test==0) print}'

If you need to pass a variable to awk use the -v option, however for array it is a bit tricker but the following syntax should work. 如果需要将变量传递给awk,请使用-v选项,但是对于数组而言,这有点麻烦,但是以下语法应该可以使用。

A=( $( ls -1p ) ) #example of list to be passed to awk (to be adapted to your needs)

awk -v var="$A" 'BEGIN{split(var,list,"\n")}END{ for (i in list) print i}'

与印第安人相同

ARR=("34" "56" "12");regex=" ${ARR[*]} ";regex="'^${regex// /\\|^}'";grep -w $regex infile

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

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