Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk's $1 conflicts with $1 in shell script

Tags:

bash

shell

awk

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?

like image 239
James Bond Avatar asked Mar 04 '12 08:03

James Bond


People also ask

What is meant by $1 in shell script?

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.

What does [- Z $1 mean in Bash?

$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.

What is $? == 0 in shell script?

$? 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.

What is role of $0 $? And $# in shell scripting?

$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.


2 Answers

A variable is fine too.

awk -F, -v needle="$1" '$1 ~ needle {print "is good"}' < input.csv
like image 118
Ignacio Vazquez-Abrams Avatar answered Sep 21 '22 14:09

Ignacio Vazquez-Abrams


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
like image 40
Adrian Pronk Avatar answered Sep 17 '22 14:09

Adrian Pronk