使用 awk 或 sed 提取具有特定模式的部分行

Pim*_*esh 19 sed awk text-processing

我有一个关于awk/sed运算符的问题。我有一个大文件,其中重复了以下几行

Expression loweWallrhoPhi :  sum=-6.97168e-09
Expression leftWallrhoPhi :  sum=6.97168e-09
Expression lowerWallPhi :  sum=-5.12623e-12
Expression leftWallPhi :  sum=5.12623e-12
Expression loweWallrhoUSf :  sum=-6.936e-09
Expression leftWallrhoUSf :  sum=6.97169e-09
Expression lowerWallUSf :  sum=-5.1e-12
Expression leftWallUSf :  sum=5.12624e-12
Run Code Online (Sandbox Code Playgroud)

我想sum在每种情况下将关键字后面的值提取到一个单独的文件中。可以一次性完成吗?

αғs*_*нιη 27

grep

grep -oP 'sum=\K.*' inpufile > outputfile
Run Code Online (Sandbox Code Playgroud)

grep with -P(perl-regexp) 参数支持\K,用于忽​​略之前匹配的字符。

awk

awk -F"=" '{ print $NF; }' inputfile > outputfile
Run Code Online (Sandbox Code Playgroud)

awk 中,该变量NF表示当前记录/行中的字段总数,它也指向最后一个字段编号,因此$NF它的值也是如此。

sed

sed 's/^.*sum=//' inpufile > outputfile
Run Code Online (Sandbox Code Playgroud)

^.*=sum用空白字符替换.*行(^)开头和最后一个字符()之间的所有字符()sum=

结果:

-6.97168e-09
6.97168e-09
-5.12623e-12
5.12623e-12
-6.936e-09
6.97169e-09
-5.1e-12
5.12624e-12
Run Code Online (Sandbox Code Playgroud)

cut

cut -d'=' -f2 inputfile > outputfile
Run Code Online (Sandbox Code Playgroud)

如果您想将相同的值分别保存到同一个文件中,awk您可以执行以下操作:

awk -F"=" '{print $NF >($NF); }' inputfile > outputfile
Run Code Online (Sandbox Code Playgroud)


jim*_*mij 6

如果我正确理解了您只想在 之后获取值的问题=,并根据第二个字段 (?) 将这些值存储在单独的文件中。如果我是对的尝试这样的事情:

$ awk -F'[ =]' '{print $6>"file_"$2".txt"}' file
Run Code Online (Sandbox Code Playgroud)

结果:

$ ls -1
  file_leftWallPhi.txt
  file_leftWallUSf.txt
  file_leftWallrhoPhi.txt
  file_leftWallrhoUSf.txt
  file_loweWallrhoPhi.txt
  file_loweWallrhoUSf.txt
  file_lowerWallPhi.txt
  file_lowerWallUSf.txt

$ cat  file_leftWallPhi.txt
  5.12623e-12
Run Code Online (Sandbox Code Playgroud)