linux 命令,awk与bash变量的多种用法
在awk中使用shell变量,使用“‘$var’”:
awk '{if(NR>2) print "'$1'"}' "$1".txt > "$1"count.txt;
#在命令部分使用"''",在外部使用“ ”
若含空格使用““$var””
在bash中使用awk结果作为变量:
for i in `seq 1 59`#seq是linux命令,此处``与$()用法相同,即运行seq命令将结果运用到for命令中
do
eval $(awk '{if(NR=="'$i'")printf("num=%s",$0)}' SampleMoreThanTwo.txt )
#等于在cmd中运行num=$0,
#$0是SampleMoreThanTwo.txt所有字串,即产生一个shell变量,num,
#各种linux命令都可以用$num来使用它,如echo "$num"
eval $(awk '{if(NR=="'$i'")printf("fq1=%s",$0)}' Sample_fq_morethantwo_1.txt )
eval $(awk '{if(NR=="'$i'")printf("fq2=%s",$0)}' Sample_fq_morethantwo_2.txt )
mkdir $num;
awk '{if($1~/fastq1/){split($0,a,"=");gsub(a[2],"'$fq1'")}print $0}' config_sample_83083.txt > $num/temp.txt
#split()命令创建数组,gsub进行替换,
#其中使用fq1这一shell变量,因此用"‘’"
#在linux命令外部不需要加引号
awk '{if($1~/fastq2/){split($0,a,"=");gsub(a[2],"'$fq2'")}print $0}' $num/temp.txt > $num/config_$num.txt
rm $num/temp.txt
done
注:
eval is a built-in Linux command which is used to execute arguments as a shell command. It combines arguments into a single string and uses it as an input to the shell and execute the commands.
使用eval $()可以让awk通过输出的方式向bash传递变量,使用print及printf都可以