Skip to content
Advertisement

Regular expression to search column in text file

I am having trouble getting a regular expression that will search for an input term in the specified column. If the term is found in that column, then it needs to output that whole line. These are my variables:

sreg = search word  #Example: Adam
file = text file   #Example: Contacts.txt
sfield = column number   #Example: 1

the text file is in this format with a space being the field seperator, with many contact entries:

    First Last Email Phone Category    
    Adam aster junfmr@ 8473847548 word
    Jeff Williams 43wadsfddf@ 940342221995 friend
    JOhn smart qwer@qwer 999999393 enemy
    yooun yeall adada 111223123 other
    zefir sentr jjdirutk@jd 8847394578 other

I’ve tried with no success:

grep "$sreg" "$file" | cut -d " " -f"$sfield"-"$sfield"
awk -F, '{ if ($sreg == $sfield) print $0 }' "$file"
awk -v s="$sreg" -v c="$sfield" '$c == s { print $0 }' "$file"

Thanks for any help!

Advertisement

Answer

awk may be the best solution for this:

awk -v field="$field" -v name="$name" '$field==name' "$file"

This checks if the field number $field has the value $name. If so, awk automatically prints the full line that contains it.

For example:

$ field=1
$ name="Adam"
$ file="your_file"
$ awk -v field="$field" -v name="$name" '$field==name' "$file"
Adam aster junfmr@ 8473847548 word

As you can see, we give the parameters using -v var="$bash_var", so that you can use them inside awk.

Also, the space is the field separator, so you don’t need to specify it since it is the default.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement