awk匹配/加入两个文件,其中1是变量

时间:2013-02-06 15:04:44

标签: awk

大家好我使用两个物理文件使awk正常工作:

awk 'NR==FNR { _[$1]=$2 } NR!=FNR { if(_[$2] != "") print $0"  "_[$2]}' codes.txt text.txt 

我要做的是:而不是使用物理文件而是使用变量代替第二个文件..

awk 'NR==FNR { _[$1]=$2 } NR!=FNR { if(_[$2] != "") print $0"  "_[$2]}' codes.txt $variable

因为我必须将结果导出到物理文件,然后使用此命令将其他文件值映射到第一个文件...

我试过了

echo $variable|awk 'NR==FNR { _[$1]=$2 } NR!=FNR { if(_[$2] != "") print $0"  "_[$2]}' codes.txt

没有奏效:(

正如这里所说的那样:

cat text.txt 
564 ERR0001
535 ERR0002

 cat codes.txt 
ERR0001 This_is_error_1
ERR0002 This_is_error_2

 awk 'NR==FNR { _[$1]=$2 } NR!=FNR { if(_[$2] != "") print $0"  "_[$2]}' codes.txt text.txt 
564 ERR0001  This_is_error_1
535 ERR0002  This_is_error_2

 awk 'NR==FNR { _[$1]=$2 } NR!=FNR { if(_[$2] != "") print $0"  "_[$2]}' codes.txt text.txt |tr "_" " "
564 ERR0001  This is error 1
535 ERR0002  This is error 2

这是失败:

gg=$(cat text.txt)

echo $gg
564 ERR0001 535 ERR0002

awk 'NR==FNR { _[$1]=$2 } NR!=FNR { if(_[$2] != "") print $0"  "_[$2]}' codes.txt $gg |tr "_" " "
awk: (FILENAME=codes.txt FNR=2) fatal: cannot open file `564' for reading (No such file or directory)

IFS=' ';
echo $gg
564 ERR0001
535 ERR0002

awk 'NR==FNR { _[$1]=$2 } NR!=FNR { if(_[$2] != "") print $0"  "_[$2]}' codes.txt $gg |tr "_" " "
awk: (FILENAME=codes.txt FNR=2) fatal: cannot open file `564' for reading (No such file or directory)

如建议加入:

join -1 2 -2 1 text.txt codes.txt 
ERR0001 564 This_is_error_1
ERR0002 535 This_is_error_2

join -1 2 -2 1 $gg codes.txt 
join: extra operand `ERR0002'
Try `join --help' for more information.

echo $gg
564 ERR0001
535 ERR0002

由tripleee回答

echo $gg|join -1 2 -2 1 -  codes.txt 
ERR0001 564 This_is_error_1
ERR0002 535 This_is_error_2

 echo $gg|awk 'NR==FNR { _[$1]=$2 } NR!=FNR { if(_[$2] != "") print $0"  "_[$2]}' codes.txt - |tr "_" " "
564 ERR0001  This is error 1
535 ERR0002  This is error 2

2 个答案:

答案 0 :(得分:1)

您可以echo变量并将其传递给任何读取标准输入的命令。

对于它的价值,许多Unix实用程序接受文件名参数-来表示标准输入。

echo "$gg" | sort | join -1 2 -2 1 - text.txt

最新版本的Bash也有<<<"$gg" here-string运算符。

答案 1 :(得分:0)

{{}}会为你做这件事:

$ join -1 2 -2 1 text.txt codes.txt