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
.
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
.
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.
just as a disclaimer, awk isn't the right tool for this job — i'm assuming your actual use case is more complex and justified, so thanks for distilling it!
This specific issuse looks like it comes down to two things, variable "expansion" and passing args from bash to awk.
$
once you prefix a awk variable with $
, it will immediately make that a reference to a field: which is weird if you're used to the shell, php, or perl.
so an input like this
thing alive
cat yes
lamp no
piped through awk 'BEGIN{alive=2}{print $alive}'
will yield
alive
yes
no
while awk 'BEGIN{alive=2}{print alive}'
would yield
2
2
2
When mixing awk with bash, things get a little strange; hopefully that helps with the first part.
if you're set on using awk, and setting awk vars in the bash command, you're probably looking for this:
if [[ $1 = "-c" ]] && [[ $2 =~ ^[a-z A-Z]+$ ]]
then
awk -v var="$2" 'index($0, var)' something.txt
fi
note: the index($0, var)
is short for if (index($0, var)) { print $0 }
admittedly, it's not a "pretty" solution, but that gets back to awk being the wrong tool for the job. For a full awk solution check out ARGV
and ARGC
index
, but the whole line. But I agree that grep
is much simpler.
– Sparhawk
Jan 09 '16 at 21:47
grep
? That's the tool for the job. Simple is usually better. – Wildcard Jan 09 '16 at 20:59