Bash – Use a shell variable with Awk

awkbashshell

I have this:

if [[ $1 = "-c" ]] && [[ $2 =~ ^[a-z A-Z]+$ ]]
then
awk -v var="$2" '{print $2}' something.txt
fi

What I want is with a comand like -c abc to show the lines in something.txt that include abc.

Best Answer

Use grep:

grep abc something.txt

Also note that using $2 in the shell refers to the second argument (as you seem to know), but in awk it is different. Your question seems to show a misunderstanding of this so I'll clarify it.

The shell requires the $ to refer to the value of a variable. So you refer to a variable named myvar by writing $myvar.

In awk to refer to a variable named myvar you just use its name—myvar. To refer to a literal string containing the letters m-y-v-a-r, you type "myvar".

The $ in awk is to refer to the field with a specific number. So $2 refers to the second field of the current line of the file. Or if you set myvar = "4", then $myvar refers to the fourth field of the file.

For just printing all lines of a file that match a given pattern, use grep—that's what it's designed for.

Related Question