Skip to content
Advertisement

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

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement