[英]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
這些行可能不止一次並且具有不同的值。 我想替換 mseconds 值。 所以,預期的輸出是:
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
而且我還考慮為每個案例(Total、Stage 1 和 Stage 2)都這樣做,但如果有更實用的東西,我將非常感激。
使用sed
(我使用 GNU sed,具體來說)來實現結果會更容易:
sed -E '/execution time/s/.*\(([0-9]*) mseconds\)/\1/'
僅保留數字部分\\(([0-9]*) mseconds\\)
在模式execution time
。 ([0-9]*)
用作反向引用,以便通過使用\\1
輸出所需的數字,而\\(
和\\)
表示文字括號。
你能不能試試以下。
awk '
/execution time/ && match($0,/[0-9]+ mseconds/){
val=substr($0,RSTART,RLENGTH)
sub(/ [a-zA-Z]+/,"",val)
print val
val=""
next
}
1
' Input_file
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.