bash 在单行上回显打印变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1041170/
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
echo printing variables on single line
提问by Victor
I have two variables:
我有两个变量:
export portNumber=8888^M
export loginIP_BASE=10.1.172.2^M
I'm trying to print them both on a single line separated by a colon ':'. It should look like "10.1.172.2:8888"
我试图将它们都打印在由冒号“:”分隔的一行上。它应该看起来像“10.1.172.2:8888”
echo -n 'Login IP:'
echo -n $loginIP_BASE
echo -n ':'
echo $portNumber
but it it prints this instead:
但它会打印这个:
:8888 IP:10.1.172.2
Why is it doing that? How can I get it to do what I want?
为什么要这样做?我怎样才能让它做我想做的事?
Also, the variables are preexisting from another file, so I did not write them myself. What does the "^M" do?
此外,这些变量预先存在于另一个文件中,所以我没有自己编写它们。“^M”有什么作用?
回答by blaxter
In Windows a tipical new line is \r\n (in *nix systems is just \n).
在 Windows 中,典型的新行是 \r\n(在 *nix 系统中只是 \n)。
\ris carriage return.
\r是回车。
\nis new line.
\n是新行。
^Mis \r, so after writing $loginIP_BASE you are at position 0 of the actual line.
^M是\r,因此在写入 $loginIP_BASE 后,您位于实际行的位置 0。
If you want to remove all those ^M you can do it in vim o with sed using:
如果您想删除所有这些 ^M,您可以在 vim o 中使用 sed 进行操作:
sed s/{ctrl+v}{ctrl+m}// file > new_file
({Ctrl+v} means press ctrl and then v)
({Ctrl+v} 表示按 ctrl 然后按 v)
回答by RichieHindle
The file has been transferred from Windows in binary mode, and still has carriage return characters at the ends of the lines.
该文件已以二进制模式从 Windows 传输,并且在行尾仍有回车符。
They are your ^Msymbols, and they are causing the text position to return to the start of the line when the values are displayed - the carriage return at the end of the first value makes the second value display at the start of the line again, overwriting part of the first value.
它们是您的^M符号,它们导致文本位置在显示值时返回到行首 - 第一个值末尾的回车使第二个值再次显示在行首,覆盖第一个值的一部分。
The right fix is to transfer the file from Windows using text mode transfer, or to run dos2unix on the file after you've transferred it. (Or if the file isn't going to be transferred from Windows again, just delete the ^Mcharacters!)
正确的解决方法是使用文本模式传输从 Windows 传输文件,或者在传输文件后在文件上运行 dos2unix。(或者,如果文件不会再次从 Windows 传输,只需删除^M字符即可!)
回答by Gvtha
Use dos2unix command:
使用 dos2unix 命令:
dos2unix filename
One more trick to remove Ctrl+M in vi editor:
在 vi 编辑器中删除 Ctrl+M 的另一个技巧:
:%s/^V^M//g

