Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make AWK use the variable created in Bash Script [duplicate]

Tags:

linux

bash

unix

awk

I have script that looks like this

#!/bin/bash
#exampel inputfile is "myfile.txt"
inputfile=$1
basen=`basename $inputfile .txt`  # create basename

cat $inputfile | 
awk '{print $basen "\t" $3}  # this doesn't print "myfile" but the whole content of it.

What I want to do above is to print out in AWK the variable called 'basen' created before. But somehow it failed to do what I hoped it will.

So for example myfile.txt contain these lines

foo bar bax
foo qux bar

With the above bash script I hope to get

myfile bax
myfile bar

What's the right way to do it?

like image 996
neversaint Avatar asked Jun 23 '10 03:06

neversaint


People also ask

What is awk '{ print $2 }'?

awk '{ print $2; }' prints the second field of each line. This field happens to be the process ID from the ps aux output. xargs kill -${2:-'TERM'} takes the process IDs from the selected sidekiq processes and feeds them as arguments to a kill command.

What does $1 $2 indicate in the awk file?

The variable $1 represents the contents of field 1 which in Figure 2 would be "-rwxr-xr-x." $2 represents field 2 which is "1" in Figure 2 and so on. The awk variables $1 or $2 through $nn represent the fields of each record and should not be confused with shell variables that use the same style of names.


2 Answers

The -v flag is for setting variables from the command line. Try something like this:

awk -v "BASEN=$basen" '{print BASEN "\t" $3}'
like image 173
drawnonward Avatar answered Sep 21 '22 18:09

drawnonward


You can use it like this.

for i in `find $1 -name \*.jar`
do
jar tvf $i| awk -F '/' '/class/{print "'${i}'" " " $NF }' >> $classFile
done

You should use

"'${i}'"

in AWK to use the

$i

created in Bash Script.

like image 41
iamxhu Avatar answered Sep 18 '22 18:09

iamxhu