
我有一個腳本日誌文件,看起來有點像這樣:
2012-9-16
Did something
Did 345 things
Script time: 244 seconds
2012-9-17
Did yet something
Did another thing 23 times
Script time: 352 seconds
2012-9-18
Did something special for 34 seconds 51 times
Did nothing at all
Script time: 122 seconds
N
我想找出行中的最大值Script time: N seconds
。但是,我需要保留上下文,因此簡單地刪除其中不包含的所有行Script time
並不是一個可行的解決方案。
目前,我正在 grep 尋找帶有 的行Script time
,然後對它們進行排序以找到最高值,然後返回原始檔案並蒐索該值。但是,如果有更直接的方法,我很想知道。
這是在最近的 CentOS 上的 Vim 7.3 上。如果可能的話我比較願意留在VIM。
答案1
我不確定你是否可以在 vim 中使用 shell 命令,但這將是我的解決方案......有點 hacky:
cat test.txt | sed ":a;N;$!ba;s/\n\n/###/g" | sed ":a;N;$!ba;s/\n/ /g" | sed "s/###/\n/g" | sort "-nrt:" -k2 | head -1
蘇...簡短的解釋:
cat test.txt # Can be omitted as sed does also accept files,
# but I like it for readability
sed ":a;N;$!ba;s/\n\n/###/g" # Replace the double-newlines with a placeholder
sed ":a;N;$!ba;s/\n/ /g" # Replace all newlines with a space
sed "s/###/\n/g" # Replace all placeholders with a newline
sort "-nrt:" -k2 # Sort numeric, reverse, use the : as delimiter and
# use the second field for sorting
head -1 # Give us only the first line
已sed
採取來自這個堆疊溢位問題。
答案2
嘗試awk
:
awk -vRS='' 'max<$(NF-1){max=$(NF-1);tmp=$0};END{print tmp}' input.txt
來電:awk
vim
:%!awk ...
答案3
我用這個VIM函數找到了解決方案:
function Find()
execute "g!/Script/d"
execute "sort"
normal G
normal 0v$"ay
normal u
execute "call search('".@a."')"
endfunction