Scripting bash脚本变量在使用cp时会产生奇怪的结果

Scripting bash脚本变量在使用cp时会产生奇怪的结果,scripting,carriage-return,cp,Scripting,Carriage Return,Cp,如果在bash脚本中使用cp,复制的文件将在目标文件名周围有奇怪的字符。 目标名称来自一个操作的结果,它被放在一个变量中,回显变量显示正常输出 目标是以字符串命名文件 #!/bin/bash newname=`cat outputfile | grep 'hostname ' | sed 's/hostname //g' newecho=`echo $newname` echo $newecho cp outputfile "$newecho" 如果我启

如果在bash脚本中使用cp,复制的文件将在目标文件名周围有奇怪的字符。 目标名称来自一个操作的结果,它被放在一个变量中,回显变量显示正常输出

目标是以字符串命名文件

    #!/bin/bash
    newname=`cat outputfile | grep 'hostname ' | sed 's/hostname //g'
    newecho=`echo $newname`
    echo $newecho
    cp outputfile "$newecho"
如果我启动脚本,回音看起来正常

    $ ./rename.sh
    mo-swc-56001
但是,文件的名称不同

    ~$ ls
    'mo-swc-56001'$'\r'
如您所见,该文件包含echo未显示的额外字符

编辑:文件的换行符如下所示

    # file outputfile
    outputfile: ASCII text, with CRLF, CR line terminators
我尝试了各种可能的方法来摆脱^M charachter,但这是数百次尝试中的一个例子

    # cat outputfile | grep 'hostname ' | sed 's/hostname //g' | cat -v
    mo-swc-56001^M

    # cat outputfile | grep 'hostname ' | sed 's/hostname //g' | cat -v |  sed 's/\r//g' | cat -v
    mo-swc-56001^M
这条新线将留在那里。有什么想法吗


编辑:疯狂,唯一的方法是对输出执行dos2unix…

看起来您的输出文件中有
\r
字符,因此您可以在其中添加逻辑以删除它们,然后再试一次

#!/bin/bash
##remove control M first from outputfile  by tr command.
tr -d '\r' < outputfile  > temp && mv temp outputfile
newname=$(sed 's/hostname //g' outputfile)
newecho=`echo $newname`
echo $newecho
cp outputfile "$newecho"
#/bin/bash
##首先通过tr命令从outputfile中删除控件M。
tr-d'\r'temp&mv temp outputfile
newname=$(sed's/hostname//g'outputfile)
newecho=`echo$newname`
echo$newecho
cp输出文件“$newecho”

唯一的方法是使用dos2unix

@James Biffi,你能告诉我这是否对你有帮助吗?我在问题中添加了一些细节,有一个换行符我无法摆脱。@JamesBiffi,请检查我的编辑命令,让我知道这是否对你有帮助?可能是重复的