简体   繁体   中英

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")?

#!/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")?

You could use bash to interpolate the string to a regex pattern used in Awk , by changing the IFS value to a | 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.

The $() runs in the sub-shell do that the value of IFS is not reflcted in the parent shell. 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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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