如何使用 grep 查找特定的数字字符串并将其移动到新的测试文件

How to use grep to find a specific string of numbers and move that to a new test file

我是 linux 和 grep 的新手,我正在寻找有关如何使用 grep 的指导。我正在尝试从文本文件中获取两个特定数字。我将需要对数千个文件执行此操作,因此我相信使用 grep 或类似工具对我的心理健康最有利。

我正在使用的文本文件如下所示:

*Average spectrum energy:    0.00100 MeV
 Average sampled energy :    0.00100 MeV [ -0.0000%]
 K/phi    = <E*mu_tr/rho>         = 6.529719E+02 10^-12 Gy cm^2 [ 0.0008%]
 Kcol/phi = <E*mu_tr/rho>*(1-<g>) = 6.529719E+02 10^-12 Gy cm^2 [ 0.0008%]
 <g>                              =   1.0000E-15 [  0.4264%]
 1-<g>                            =     1.000000 [  0.0000%]
<mu_tr/rho> = <E*mu_tr/rho>/Eave         = 4.075530E+03   cm^2/g [ 0.0008%]
<mu_en/rho> = <E*mu_tr/rho>*(1-<g>)/Eave = 4.075530E+03   cm^2/g [ 0.0008%]
<E*mu_en/rho>                            = 4.075530E+00   MeV cm^2/g

我希望从中提取的值是“0.00100”和“4.075530E+00”。

目前我正在使用 grep -iE "Average spectrum energy|<E*mu_en/rho>" * 这让我可以看到完整的行,但我不太确定如何优化搜索以只显示数字而不是整行。这可能使用 grep 吗?

至于将数字移动到新文件中,我相信命令是> newdata.txt。我的问题是,在将它与 grep 一起使用时,您可以更改它将数据写入新文本文件的方式吗?我正在寻找这样的数字格式:

0.00100001    3.4877754595352117
0.00100367    3.4665273232204363
0.00100735    3.4453747056004884
0.00101104    3.4243696230289187
0.00101474    3.4035147003587718

同样可以使用 grep > newdata.txt 吗?

我非常感谢人们能给我的任何帮助或指导。谢谢。

I'm not quite sure why it was giving the 4.075530E+03 value.

那是因为*具有重复前一项任意次数(包括零次)的特殊含义,所以模式<E*mu_en/rho>与文本<E*mu_en/rho>不匹配,而是 < 任意数量的 E mu_en/rho>,i。 e.特别是 <mu_en/rho>。要逃避这种特殊含义并匹配文字 *,请在前面加上反斜杠,i。 e. <E\*mu_en/rho>.

I am not quite sure how to refine the search to only show me the numbers instead of just the whole line. Is this possible using grep?

如果PCRE (grep -P)在系统中可用。为了只 (-o) 显示数字,我们可以使用 Resetting the match start\K 的特性。您修改后的 grep 命令是:

grep -hioP "(Average spectrum energy: *|<E\*mu_en/rho> *= )\K\S*" *

(选项 -h 删除文件名,模式项 \S 表示 不是白色 space)。

when using this with grep can you change how it writes the data to the new text file?

grep 本身不能改变数字的格式(除非可能会截掉数字)。如果你想要这个,我们需要另一个工具。现在,由于我们需要另一个工具,我会考虑使用一个能够完成整个工作的工具,例如。 G。 awk:

awk '
/Average spectrum energy/ { printf "%.8f    ",  }
/<E\*mu_en\/rho>/         { printf "%.16f\n",  }
' * >newdata.txt