Can you insert a variable by passing it as a regular expression in the awk command?

Asked

Viewed 42 times

1

Example:

VARIAVEL="Pará"

echo "$VARIAVEL" | awk '/^P/ { print $1 }'

What this does is just search for any word started with a capital letter P.

Okay, so far so good!


Now, I want to know if you can insert this $VARIABLE between the regular expression bar of awk '/$VARIAVEL/ { print $1}'.?

The intention is to search a single line from a file.

This is a template of the file in question:

Pará                     Norte
Bahia                   Nordeste
Paraná                 Sul
Goiás                   Centro-Oeste

.. and so on.

What I’ve been doing manually is:

FILE=/tmp/list_states_brazilians.txt

awk '/Bahia/ { print $2 }' $ARQUIVO

Output house with the expression 'Bahia' of the first column and is returned the second column 'Northeast'.

But I want to use a variable as input for regular expression instead of having to type manually.

This is necessary since I will use another script to select the word to be included within the awk.

So the question again is .. is it possible? Include a variable within the regular expression of awk?

The problem here is find a way to do the inclusion of the variable?

1 answer

1


you have to use ~, as $0 ~ variable the $1 ~ variable.

awk -v patt="Bahia" '$0 ~ patt {print $2}' fichero

Example:

$ awk -v patt="Bahia" '$1 ~ patt {print $2}' <<< "Bahia blabla"
blabla
  • The first example of your answer works for me. I did so: ARQUIVO=/tmp/lista.txt awk -v VARIAVEL="Bahia" -F "'" '$0 ~ VARIAVEL {print $2}' $ARQUIVO and got the expected return NORTHEAST. Note that I am adding another argument, the -F from which to filter the contents between the single quotes between the apostrophes. Because of this, I answer you -, in my list the second column that designates each region of a Brazilian state is in simple quotes 'NORTHEAST'. Anyway his example was a brief clarification about this awk structure that I have not mastered yet.

  • Already in the second example: awk -v patt="Bahia" '$1 ~ patt {print $2}' <<< "Bahia blabla" when running at the terminal [land] I was unsuccessful [success]. I get the following error: sh: syntax error: unexpected redirection. I noticed that my SHELL is working with former Bourn Shell. So as I have installed both Mr. Bash and Mr. Bourn. Just type Bash into the terminal and then run the command line of the second example of the answer. And so to do, I had feedback shown: Blabla

Browser other questions tagged

You are not signed in. Login or sign up in order to post.