Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Howto Pass A String as Parameter in AWK within Bash Script

Tags:

linux

bash

unix

awk

I have a text file which I want to filter using awk. The text file looks like this:

foo 1
bar 2
bar 0.3
bar 100
qux 1033

I want to filter those files with awk inside a bash script.

#!/bin/bash

#input file
input=myfile.txt

# I need to pass this as parameter
# cos later I want to make it more general like
# coltype=$1
col1type="foo"   

#Filters
awk '$2>0 && $1==$col1type' $input

But somehow it failed. What's the right way to do it?

like image 757
neversaint Avatar asked Mar 16 '10 01:03

neversaint


2 Answers

pass it in using -v option of awk. that way, you separate out awk variables and shell variables. Its neater also without extra quoting.

#!/bin/bash

#input file
input=myfile.txt

# I need to pass this as parameter
# cos later I want to make it more general like
# coltype=$1
col1type="foo"   

#Filters
awk -vcoltype="$col1type" '$2>0 && $1==col1type' $input
like image 188
ghostdog74 Avatar answered Nov 15 '22 07:11

ghostdog74


"double quote single quote"

awk '{print "'$1'"}'


example:

$./a.sh arg1 
arg1


$cat a.sh 
echo "test" | awk '{print "'$1'"}'


linux tested

like image 43
sudhakar Avatar answered Nov 15 '22 07:11

sudhakar