从日志文件中删除 ^M 字符

Ram*_*Ram 6 command-line shell newlines

从日志文件中删除 ^M 字符。

在我的脚本中,我将程序的输出重定向到日志文件。我的日志文件的输出包含一些 ^M(换行符)字符。我需要在运行时删除它们。

我的命令:

$ java -jar test.jar >> test.log 
Run Code Online (Sandbox Code Playgroud)

test.log 已:

启动脚本... ^M 启动脚本...初始化

slm*_*slm 18

转换独立文件

如果您运行以下命令:

$ dos2unix <file>
Run Code Online (Sandbox Code Playgroud)

<file>将所有剥夺了^ M字符。如果你想<file>保持完整,那么只需dos2unix像这样运行:

$ dos2unix -n <file> <newfile>
Run Code Online (Sandbox Code Playgroud)

解析命令的输出

如果需要通过一个管道,做他们的命令链的一部分,你可以使用任意数量的工具,如trsedawk,或perl做到这一点。

tr

$ java -jar test.jar | tr -d '^M' >> test.log
Run Code Online (Sandbox Code Playgroud)

sed

$ java -jar test.jar | sed 's/^M//g' >> test.log
Run Code Online (Sandbox Code Playgroud)

awk

$ java -jar test.jar | awk 'sub(/^M/,"")' >> test.log
Run Code Online (Sandbox Code Playgroud)

perl

$ java -jar test.jar | perl -p -e 's/^M//g' >> test.log
Run Code Online (Sandbox Code Playgroud)

键入 ^M

输入时请^M务必通过以下方式之一输入:

  1. 正如Control+ v+M而不是Shift+ 6+ M
  2. 作为反斜杠 r,即 ( \r)。
  3. 作为八进制数 ( \015)。
  4. 作为十六进制数 ( \x0D)。

为什么这是必要的?

^M是在 Windows 平台上如何终止行尾的一部分。每个行尾都以回车符后跟换行符结束。

在 Unix 系统上,行尾仅由换行符终止。

  • 换行符 =0x0A十六进制,也写成\n.
  • 回车符 =0x0D十六进制,也写成\r.

例子

如果将输出通过管道传输到诸如od或 之类的工具,则可以看到这些hexdump。这是一个示例文件,其中行终止回车符 + 换行符。

$ cat sample.txt
hi there
bye there
Run Code Online (Sandbox Code Playgroud)

你可以看到他们hexdump\r+ \n

$ hexdump -c sample.txt 
0000000   h   i       t   h   e   r   e  \r  \n   b   y   e       t   h
0000010   e   r   e  \r  \n                                            
0000015
Run Code Online (Sandbox Code Playgroud)

或者作为他们的十六进制0d+ 0a

$ hexdump -C sample.txt 
00000000  68 69 20 74 68 65 72 65  0d 0a 62 79 65 20 74 68  |hi there..bye th|
00000010  65 72 65 0d 0a                                    |ere..|
00000015
Run Code Online (Sandbox Code Playgroud)

运行这个sed 's/\r//g'

$ sed 's/\r//g' sample.txt |hexdump -C
00000000  68 69 20 74 68 65 72 65  0a 62 79 65 20 74 68 65  |hi there.bye the|
00000010  72 65 0a                                          |re.|
00000013
Run Code Online (Sandbox Code Playgroud)

您可以看到sed已删除该0d字符。

使用 ^M 查看文件而不转换?

是的,您可以使用它vim来执行此操作。您可以fileformat在 vim 中设置设置,这将具有像我们上面所做的那样转换文件的效果,或者您可以在vim视图中更改文件格式。

更改文件格式

:set fileformat=dos
:set fileformat=unix
Run Code Online (Sandbox Code Playgroud)

您也可以使用速记符号:

:set ff=dos
:set ff=unix
Run Code Online (Sandbox Code Playgroud)

或者,您可以更改视图的文件格式。这种方法是无损的:

:e ++ff=dos
:e ++ff=unix
Run Code Online (Sandbox Code Playgroud)

在这里你可以看到我打开我们的^M文件,sample.txtvim

           vim dos #1 的 ss

现在我正在转换视图中的文件格式:

           vim dos 的 ss #2

这是转换为unix文件格式时的样子:

           vim dos #3 的 ss

参考