大家好,我使用两个物理文件使 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
三人组回答
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