找到一个文件的一行,提取其中的一部分并替换在 Bash 中的相同位置
Find a line of a file, extract part of it and replace in the same place in Bash
我有一个包含以下内容的大文件(这是它的摘录):
Total execution time (hh:mm:ss.ms): 00:00:8,4880 (8488 mseconds)
Error 0.00044
Stage 1 execution time (hh:mm:ss.ms): 00:00:7,0430 (7043 mseconds)
Stage 2 execution time (hh:mm:ss.ms): 00:00:1,4450 (1445 mseconds)
Total execution time (hh:mm:ss.ms): 00:00:0,0170 (17 mseconds)
Number of variables 6
这些行可能不止一次并且具有不同的值。我想替换为毫秒值。所以,预期的输出是:
8488
Error 0.00044
7043
1445
17
Number of variables 6
我已经试过了,但我不知道如何替换行中提取的值:
grep "Total execution time (hh:mm:ss.ms):" file.txt | cut -d " " -f6 | cut -d "(" -f2
而且我也在考虑对每个案例(总计、第 1 阶段和第 2 阶段)执行此操作,但如果有更实用的东西,我将不胜感激。
使用sed
(具体来说,我使用GNU sed)会更容易获得结果:
sed -E '/execution time/s/.*\(([0-9]*) mseconds\)//'
仅保留数字部分 \(([0-9]*) mseconds\)
与模式 execution time
一致。 ([0-9]*)
用作反向引用,以便通过使用 </code> 输出所需的数字,而 <code>\(
和 \)
表示文字括号。
能否请您尝试以下。
awk '
/execution time/ && match([=10=],/[0-9]+ mseconds/){
val=substr([=10=],RSTART,RLENGTH)
sub(/ [a-zA-Z]+/,"",val)
print val
val=""
next
}
1
' Input_file
我有一个包含以下内容的大文件(这是它的摘录):
Total execution time (hh:mm:ss.ms): 00:00:8,4880 (8488 mseconds)
Error 0.00044
Stage 1 execution time (hh:mm:ss.ms): 00:00:7,0430 (7043 mseconds)
Stage 2 execution time (hh:mm:ss.ms): 00:00:1,4450 (1445 mseconds)
Total execution time (hh:mm:ss.ms): 00:00:0,0170 (17 mseconds)
Number of variables 6
这些行可能不止一次并且具有不同的值。我想替换为毫秒值。所以,预期的输出是:
8488
Error 0.00044
7043
1445
17
Number of variables 6
我已经试过了,但我不知道如何替换行中提取的值:
grep "Total execution time (hh:mm:ss.ms):" file.txt | cut -d " " -f6 | cut -d "(" -f2
而且我也在考虑对每个案例(总计、第 1 阶段和第 2 阶段)执行此操作,但如果有更实用的东西,我将不胜感激。
使用sed
(具体来说,我使用GNU sed)会更容易获得结果:
sed -E '/execution time/s/.*\(([0-9]*) mseconds\)//'
仅保留数字部分 \(([0-9]*) mseconds\)
与模式 execution time
一致。 ([0-9]*)
用作反向引用,以便通过使用 </code> 输出所需的数字,而 <code>\(
和 \)
表示文字括号。
能否请您尝试以下。
awk '
/execution time/ && match([=10=],/[0-9]+ mseconds/){
val=substr([=10=],RSTART,RLENGTH)
sub(/ [a-zA-Z]+/,"",val)
print val
val=""
next
}
1
' Input_file