【问题标题】:put awk code in bash and sort the result将 awk 代码放入 bash 并对结果进行排序
【发布时间】:2012-10-23 14:53:45
【问题描述】:

我有一个用于组合 2 个文件的 awk 代码,并使用“>>”将结果添加到 file.txt 的末尾

我的代码

NR==FNR && $2!=0 {two[$0]++;j=1; next }{for(i in two) {split(i,one,FS); if(one[3] == $NF){x=$4;sub( /[[:digit:]]/, "A", $4); print j++,$1,$2,$3,x,$4 | "column -t" ">>" "./Desktop/file.txt"}}}

我想把我的 awk 放到 bash 脚本中,最后对我的 file.txt 进行排序,然后使用>再次将排序结果保存到 file.txt

我试过了

#!/bin/bash
command=$(awk '{NR==FNR && $2!=0 {two[$0]++;j=1; next }{for(i in two) {split(i,one,FS); if(one[3] == $NF){x=$4;sub( /[[:digit:]]/, "A", $4); print $1,$2,$3,$4 | "column -t" ">>" "./Desktop/file.txt"}}}}')
echo -e "$command" | column -t | sort -s -n -k4 > ./Desktop/file.txt 

但它给了我错误"for reading (no such a file or directory)"

我的错误在哪里?

提前致谢

【问题讨论】:

  • 你能给出输入文件和预期结果的例子吗?

标签: bash sorting awk


【解决方案1】:

1) 您没有为 awk 脚本指定输入文件。这个:

command=$(awk '{...stuff...}')

需要:

command=$(awk '{...stuff...}' file1 file2)

2) 您将 awk 条件“NR == ...”移动到操作部分内,使其不再作为条件运行。

3) 您的 awk 脚本输出将进入“file.txt”,因此当您在下一行回显时,“command”为空。

4) 你有未使用的变量 x 和 j

5) 您不必要地将 arg FS 传递给 split()。

等等……

我认为你想要的是:

command=$( awk '
   NR==FNR && $2!=0 { two[$0]++; next }
   {
      for(i in two) {
          split(i,one)
          if(one[3] == $NF) {
             sub(/[[:digit:]]/, "A", $4)
             print $1,$2,$3,$4 
          }
      }
    }
' file1 file2 )
echo -e "$command" | column -t >> "./Desktop/file.txt"
echo -e "$command" | column -t | sort -s -n -k4 >> ./Desktop/file.txt

但很难说。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-03
    • 2020-01-27
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    • 2022-11-20
    • 2011-06-19
    • 2015-07-29
    相关资源
    最近更新 更多