Shell – How to find a specific ‘string’ and print out the whole line

awkshell-scripttext processing

I have a file named myfile.csv containing the following:

 abc:123:myname:1231
 def:423324:arbitrary:value:string
 StackExchange:Unix:Linux

From the terminal I run ./myscript.sh def

The contents of myscript.sh is:

#!/bin/bash
key_word_I_am_looking_for=$1
my_variable=`cat myfile.csv | awk -F: -v keyword="$key_word_I_am_looking_for" '( $1 == keyword )' END{print "$@" }'`
echo "$my_variable"

I want the code to search for the word def or any other word in the first parameter in the myfile.csv ie abc or StackExchange. Once found I would like it to take the whole line out without the seperators and place it in the my_variable variable, and echo it out to the terminal (so the output would look like: def 423324 arbitrary value string when ./myscript.sh def is entered to the terminal. When ./myscript.sh StackExchange the output would be StackExchange Unix Linux ).

Where am I going wrong? Is there an alternative?

Best Answer

Your awk syntax is a little wrong.

#!/bin/bash
awk -F: -v keyword="$1" '$1 == keyword {$1=$1; print}' myfile.csv

The trick here is reassigning the value of one of the fields forces awk to recalculate $0 using the output file separator. Here, the default OFS is a space, so assigning the value of $1 to itself changes the colons to spaces.

A non-awk way to write this is:

grep "^$1:" myfile.csv | tr ":" " "

but that uses regular expression matching, not string equality