【问题标题】:Redirect awk result to text file将 awk 结果重定向到文本文件
【发布时间】:2014-06-24 17:55:45
【问题描述】:

我在一个文件中有以下几行

lines="188"
lines="24"
lines="25"

然后我提取引号(“”)内的值,并使用以下命令将这些值相加得到 237

awk -F'\"' '{count+=$2;}END{if(count>0) print count;else print 0}'

但是,我想将输出重定向到文本文件。我尝试使用重定向操作 (>) 运算符,但它一直给我错误

这是我目前所拥有的

awk -F'\"' '{count+=$2;}END{if(count>0) print count;else print 0}' > "sum.txt"

这就是错误

fatal: cannot open file '>' for reading (No such file or directory)

【问题讨论】:

  • "I tried using the redirect operation (>) operator" 显示你尝试了什么。
  • 你给文件名了吗?

标签: windows command-line awk command-line-arguments gawk


【解决方案1】:

已编辑 - 在 awk 和 cmd 之间的行中处理引号似乎存在问题。要将引号用作分隔符,请将其更改为

awk -F \x22 "{count+=$2}END{print count+0}" "input.txt" > "output.txt"

【讨论】:

  • 我认为这对他不起作用。在我的回答中查看操作的 cmets。
  • @AvinashRaj,你是对的。我没有看到报价处理中的冲突。已更正
  • @MCND,在编辑\x22 之后,这工作!谢谢!
  • @bacaviteno 为什么不在 BEGIN 块中给出 FS 值?
【解决方案2】:

您没有在命令中提及输入文件名的路径。你的命令应该是,

awk -F'"' '{count+=$2;}END{if(count>0) print count;else print 0}' inputfile > "sum.txt"

而且您也不需要在单引号内转义 FS 值 "

【讨论】:

  • 它仍然给我错误 awk: cmd. line:1: (FILENAME=temp.txt FNR=3) fatal: cannot open file `>' for read ing(没有这样的文件或目录)
  • awk -F'\"' '{count+=$2;}END{if(count>0) print count;else print 0}' temp.txt > sum.txt
  • 它如何显示` (FILENAME=temp.txt FNR=3) 无法打开文件>' for read ing (No such file or directory) 但您的实际命令是不同的。
  • 哎呀,抱歉应该是 temp.txt
  • temp.txt 文件是否存在于您的当前目录中? >前后有没有加空格?
【解决方案3】:

你可以缩短一些:

awk -F\" '{count+=$2}END{print count+0}' file > sum.txt

通过添加0,您得到的结果与您的测试相同,如果count 为空,也会打印0

【讨论】:

    【解决方案4】:

    输入文件丢失。

    awk -F'\"' '{count+=$2;}END{if(count>0) print count;else print 0}' inputfile > "sum.txt"
    

    输出文件的引号不是问题。

    【讨论】:

      猜你喜欢
      • 2015-06-23
      • 1970-01-01
      • 2012-01-03
      • 2017-10-31
      • 1970-01-01
      • 1970-01-01
      • 2011-01-08
      • 1970-01-01
      • 2011-12-27
      相关资源
      最近更新 更多