user7328234
user7328234

Reputation: 413

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

Upvotes: 1

Views: 1327

Answers (4)

ctac_
ctac_

Reputation: 2471

Near the same as Inian

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

Upvotes: 0

Inian
Inian

Reputation: 85560

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 e.g. 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

Upvotes: 4

Rahul Verma
Rahul Verma

Reputation: 3089

awk one-liner

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

Upvotes: 1

Allan
Allan

Reputation: 12438

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}'

Upvotes: 0

Related Questions