2012-06-14 63 views
0

我有两个文本文件。 hash_only.txt和final_output.txt hash_only.txt如下所示。使用bash处理文件和文本

193548 
401125 
401275 

final_output.txt如下所示。

193548  1199687744 5698758206701808640 
193548  1216464960 5698758206761818112 
193548  1216464960 5698758206778417152 
193548  4236691520 5698758206778945280 
401125  2138607488 5698762375908890880 
401125  863932288 5698762375909423360 
401125  3884158848 5698762375910044160 
401125  2609483648 5698762375911032320 

我想写一个循环,执行以下操作。

for i in `cat hash_only.txt` ; 
do 
    for j in `cat final_output.txt` ; 
      do 
        if [ $i -eq $j ] 
        then 
          echo $i $j  
        fi 
      done 
done; 

对于所有在hash_only.txt我想从“final_output.txt”的文件中提取柱2,3的值如193548,401125等,其中第1点的匹配193548,401125等,并输出 第2列,3到print_193548,print_401125等。

我该怎么做。在上面的代码中,我需要在部分代码里面放一些代码。但是我无法弄清楚,因为我不是很精通bash。

编辑:

我现在已经修改了我的脚本看起来likefor我cat hash_only.txt;

do 
     for j in `cat final_output.txt` ; 
       do 
         if [ $i -eq $j ] 
         then 
           gawk 'FNR==NR 
             { hash[$1] 
              next 
             } 
             $1 in hash { 
             print $2,$3 >> "print_"$1; 
           }' hash_only.txt final_output.txt 
         fi 
       done 
done; 

它没有创建任何名为print_ [0-9] *的文件。我不明白为什么不可以?

+1

所以你想创建一堆文件,对吧?第一个文件中的每个不同值都有一个值? –

+0

是的,这正是我想要的。 – liv2hak

+1

'gawk'命令将完成所有工作。 'if ... else' /'for ... loop'可以被删除。 – kev

回答

1
awk ' 
FNR==NR { 
    hash[$1] 
    next 
} 
$1 in hash { 
    printf("%s\t%s\n", $2, $3) > "print_"$1; 
}' hash_only.txt final_output.txt 

多么神奇,我的解决方案几乎和彼得的一模一样。

+0

你是否建议我在我的代码中的if部分之后添加这段代码?我试过了,它似乎没有工作。它只是打印出一系列值。 – liv2hak

+1

复制并粘贴到您的终端。它会在当前目录中创建两个文件('print_193548','print_401125')。 – kev

+2

'>>'应该是'>'(它在AWK中的工作方式与shell不同)。 –

2

试试这个:

nawk 'FNR==NR{a[$0];next}($1 in a){print $2,$3>$1}' hash_only.txt final_output.txt 

这实际上将创建一个名称的文件作为第一个字段,并存储在您所要求的方式输出。

+0

您可以省略括号。 –