I am writting a shell script which includes a couple of awk lines
the awk line looks like:
cat input.csv | awk -F, '$1~/$1/ {print "is good"}'
the first $1
is the first column of the input csv, the second $1
is supposed to be the first command line input of this shell script
I tried to put a \
in front of the second $
, but it seems to be not working.
Can anyone help?
Shell scripts have access to some "magic" variables from the environment: $0 - The name of the script. $1 - The first argument sent to the script. $2 - The second argument sent to the script.
$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.
$? is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. That line is testing whether the grep command succeeded. The grep manpage states: The exit status is 0 if selected lines are found, and 1 if not found.
$0 Expands to the name of the shell or shell script. This is set at shell initialization. If Bash is invoked with a file of commands (see Section 3.8 [Shell Scripts], page 39), $0 is set to the name of that file.
A variable is fine too.
awk -F, -v needle="$1" '$1 ~ needle {print "is good"}' < input.csv
cat input.csv | awk -F, '$1~/'"$1"'/ {print "is good"}'
You need to close the '
string, insert the shell $1
(inside "
in case there are special characters), then reopen the '
string.
And you may want to check whether the $1
from shell contains /
characters which will
upset the regular expression.
And as @Ignacio Vazquez-Abrams indicated, you don't need to pipe the output of cat
to awk, you can just get awk
to read the file directly. That is:
cat input.csv | awk ...
can be simplified to:
awk ... < input.csv
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With