bash Unix 脚本在每行末尾附加 ^M

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15020883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 23:21:32  来源:igfitidea点击:

Unix script appends ^M at end of each line

bashshellunix

提问by Vivek Iyer

I have a Unix shell script which does the following:

我有一个 Unix shell 脚本,它执行以下操作:

  1. creates a backup of a file
  2. appends some text to a file
  1. 创建文件的备份
  2. 将一些文本附加到文件中

Now in #2 if I insert a text, ^M gets appended on all the lines of the file.

现在在#2 中,如果我插入一个文本,^M 会附加在文件的所有行上。

For example:

例如:

echo " a" >> /cust/vivek.txt
echo " b" >> /cust/vivek.txt

vi vivek.txt
abc^M
bcd^M
a^M
b^M

Any way to avoid this?

有什么办法可以避免这种情况?

回答by dogbane

I'm not sure how echocould be producing ^Mcharacters but you can remove them by running dos2unixon your file, like this:

我不确定如何echo生成^M字符,但您可以通过dos2unix在文件上运行来删除它们,如下所示:

dos2unix /cust/vivek.txt

回答by cdarke

^Mis a carriage return, and is commonly seen when files are copied from Windows. Use:

^M是回车符,通常在从 Windows 复制文件时出现。用:

od -xc filename

that should give a low-level list of what your file looks like. If you file does not come from Windows then another possibility is that your terminal setting are not translating correctly. Check that the TERM environment variable is correct.

这应该给出您的文件的外观的低级列表。如果您的文件不是来自 Windows,那么另一种可能是您的终端设置没有正确翻译。检查 TERM 环境变量是否正确。

If the file has come from Windows, then use dos2unixor sed 's/\r//' file > file.new

如果文件来自 Windows,则使用dos2unixsed 's/\r//' file > file.new

回答by Antarus

^M are the meta characters which entered your file when it was used in windows.

^M 是在 Windows 中使用文件时进入文件的元字符。

the dos2unix command can fix this.

dos2unix 命令可以解决这个问题。

dos2unix <filename>

回答by Pavel Prochazka

Only

仅有的

sed -e "s/\r//g" file

worked for me

对我来说有效

回答by Brian Agnew

I suspect this may be an artifact of your vi settings, rather than the concatenation.

我怀疑这可能是您的 vi 设置的产物,而不是串联。

What does

有什么作用

cat -v -e filename

show ? This command will dump out your file and mark the control characters so it's clear what's reallyin your file. See also this Superuser question/answer set.

展示 ?此命令将转储您的文件并标记控制字符,以便您清楚文件中的真实内容。另请参阅此超级用户问题/答案集

回答by Gabriel Tirado

If you are using windows, you can use notepad++ and to try Edit > EOL Conversion > Unix/OSX Format, before load file to server.

如果您使用的是 Windows,您可以使用 notepad++ 并在将文件加载到服务器之前尝试编辑 > EOL 转换 > Unix/OSX 格式。