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
Unix script appends ^M at end of each line
提问by Vivek Iyer
I have a Unix shell script which does the following:
我有一个 Unix shell 脚本,它执行以下操作:
- creates a backup of a file
- appends some text to a file
- 创建文件的备份
- 将一些文本附加到文件中
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 echo
could be producing ^M
characters but you can remove them by running dos2unix
on your file, like this:
我不确定如何echo
生成^M
字符,但您可以通过dos2unix
在文件上运行来删除它们,如下所示:
dos2unix /cust/vivek.txt
回答by cdarke
^M
is 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 dos2unix
or sed 's/\r//' file > file.new
如果文件来自 Windows,则使用dos2unix
或sed '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 格式。