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?
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.– Diego Henrique
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– Diego Henrique