Linux

無法從 grep 中排除包含 ^M 的行

  • February 9, 2022

最後,我只想從中提取以下文件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 中的行由\nand not定義,因此\r您描述的是正常行為。換句話說,您的第一個和最後一個命令( thetr -d '\r'和 the sed 's/\r//g')都按預期工作,只是 grep 正在做它應該做的事情並列印整行。

要只列印一行的一部分,您需要 GNUgrep及其-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'

引用自:https://unix.stackexchange.com/questions/689463