Linux
無法從 grep 中排除包含 ^M 的行
最後,我只想從中提取以下文件
Removed '2022-01-30_01-00-05'
。Removing '2022-01-30_01-00-05'... 0.46% complete (00:03:45 remaining)^M 5.49% complete (00:00:17 remaining)^M 24.90% complete (00:00:06 remaining)^M 60.56% complete (00:00:01 remaining)^M 82.12% complete (00:00:00 remaining)^M 82.39% complete (00:00:01 remaining)^M 84.24% complete (00:00:01 remaining)^M 86.48% complete (00:00:01 remaining)^M 88.58% complete (00:00:01 remaining)^M 89.66% complete (00:00:01 remaining)^M101.08% complete (00:00:00 remaining)^M104.62% complete (00:00:00 remaining)^M ^MRemoved '2022-01-30_01-00-05'
我試過
dos2unix
了,但沒有用。我在下面嘗試了這些變體,但是當我
less output
要麼不刪除^M
字元時,要麼擷取整行:tr -d $'\r' < /file | grep "Removed" > output tr -d '^M' < /file | grep "Removed" > output tr -d ^M < /file | grep "Removed" > output sed 's/\r//g' < /file | grep "Removed" > output
該
grep
命令將列印整個匹配行,並且由於 *nix 中的行由\n
and not定義,因此\r
您描述的是正常行為。換句話說,您的第一個和最後一個命令( thetr -d '\r'
和 thesed 's/\r//g'
)都按預期工作,只是 grep 正在做它應該做的事情並列印整行。要只列印一行的一部分,您需要 GNU
grep
及其-o
選項。例如:$ grep -oP "Removed\s*'[^']+'" file Removed '2022-01-30_01-00-05'
或者,將
\r
(the^M
) 更改為換行符而不是刪除它們:$ tr '\r' '\n' < file | grep Removed Removed '2022-01-30_01-00-05'
或者
$ sed 's/\r/\n/g' file | grep Removed Removed '2022-01-30_01-00-05'