How to make AWK use the variable created in Bash Script

nev*_*int 16 unix linux bash 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.
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

With the above bash script I hope to get

myfile bax
myfile bar
Run Code Online (Sandbox Code Playgroud)

What's the right way to do it?

dra*_*ard 29

-v标志用于从命令行设置变量.尝试这样的事情:

awk -v "BASEN=$basen" '{print BASEN "\t" $3}'
Run Code Online (Sandbox Code Playgroud)

  • +1这是注入变量的最佳方法,因为即使`$ basen`包含撇号,引号或空格等特殊字符,它也能正常工作. (2认同)

小智 12

你可以像这样使用它.

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

你应该用

" '$ {I}'"

在AWK中使用

$ I

在Bash脚本中创建.

  • 使用`$()`而不是反引号.并且`find`与`for`循环一样会破坏带有空格的文件.引用你的`$ 1`变量 (2认同)