【问题标题】:using grep or awk to search and print the text into a file使用 grep 或 awk 搜索文本并将其打印到文件中
【发布时间】:2015-04-22 06:07:52
【问题描述】:

我有 500 个输出文件,我想在其中打印能量值(以粗体显示的文本)。请看一下单个输出文件

-----------------------------------------------------------------   
FINAL RESULTS
 ENERGY    -1.5576E+03   
-----------------------------------------------------------------------------

请求您使用 linux 命令帮助我根据生成的输出文件打印所有能量值并将其保存到新文件“say”列表中。我的输出文件的命名为 output1.out、output1.out、output3 .out 等等!

【问题讨论】:

  • 请尝试一些教程或添加您已经尝试过的代码!
  • 我确实试过 cat *.out | grep '"ENERGY"{print $2 $3}' >list ,它确实提供了输出文件名,但没有提供能量值,即 -1.5576E+03

标签: linux


【解决方案1】:

可能就这么简单:

grep ENERGY output*.out /dev/null

它只是从所有指定的输入文件中输出包含ENERGY 字符串的所有行,格式为:

output1.out:ENERGY 3.21 gigawatts
output2.out:ENERGY 3.141492653589 km.V/s^2
output3.out:ENERGY (hardly any)

(显然不是真实单位)。

/dev/null 的技巧只是确保文件名在只有一个的情况下仍然列出。在这种情况下,grep 的行为是只打印 没有 文件名的行,因此添加另一个输入文件可确保始终显示文件。

【讨论】:

  • 输出如下所述,同时我没有得到能量值,即-1.5576E+03 output100.out: ENERGY ----------------- ------------
【解决方案2】:

你可以使用awk:

for f in output*.out
do
    # print the filename without a newline
    echo -n $f >> nomenclature.list
    # tells awk to search for the line containing ENERGY,
    # then print the last field of the line (whitespaces as default field
    # separator)
    awk '/ENERGY/ { print $NF; }' $f >> nomenclature.list
done

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-08
    • 1970-01-01
    • 2016-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-29
    相关资源
    最近更新 更多