tags:

views:

69

answers:

5

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?

A: 

The reason is that bash variables (environment variables) are not expanded within single-quoted strings. Try replacing

'{print $basen "\t" $3}'

with

"{print \"$basen\" \"\t\" \$3}"
David Zaslavsky
+10  A: 

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

awk -v "BASEN=$basen" '{print BASEN "\t" $3}'
drawnonward
+1 This is the best way to inject a variable as it will work even if `$basen` contains special characters like apostrophes, quotes, or spaces.
John Kugelman
+1  A: 

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.

iamxhu
use `$()` instead of backticks. And `find` with `for` loop like that will break on files with spaces. Quote your `$1` variable
ghostdog74
+1  A: 

The easiest way is to make an awk variable. awk -v awkvar=$bashvar 'awkscript'.

Daenyth
+2  A: 

you can just do everything in awk

awk '{gsub(".txt","",ARGV[1]);print ARGV[1] "\t" $3}' inputfile.txt
ghostdog74