如何从shell脚本中的变量中删除回车符和换行符

时间:2022-03-05 23:48:43

I am new to shell script. I am sourcing a file, which is created in Windows and has carriage returns, using the source command. After I source when I append some characters to it, it always comes to the start of the line.

我是shell脚本的新手。我正在使用source命令获取一个文件,该文件在Windows中创建并具有回车符。在我为其添加一些字符时我来源,它总是到达行的开头。

test.dat (which has carriage return at end):

test.dat(最后有回车符):

testVar=value123

testScript.sh (sources above file):

testScript.sh(上面的文件来源):

source test.dat
echo $testVar got it

The output I get is

我得到的输出是

got it23

How can I remove the '\r' from the variable?

如何从变量中删除'\ r'?

6 个解决方案

#1


35  

yet another solution uses tr:

另一种解决方案使用tr:

echo $testVar | tr -d '\r'
cat myscript | tr -d '\r'

the option -d stands for delete.

选项-d代表删除。

#2


11  

You can use sed as follows:

您可以使用sed如下:

MY_NEW_VAR=$(echo $testVar | sed -e 's/\r//g')
echo ${MY_NEW_VAR} got it

By the way, try to do a dos2unix on your data file.

顺便说一句,尝试在数据文件上执行dos2unix。

#3


5  

use this command on your script file after copying it to Linux/Unix

将其复制到Linux / Unix后,在脚本文件上使用此命令

perl -pi -e 's/\r//' scriptfilename

#4


2  

Pipe to sed -e 's/[\r\n]//g' to remove both Carriage Returns (\r) and Line Feeds (\n) from each text line.

管道到sed -e's / [\ r \ n] // g'从每个文本行中删除回车符(\ r)和换行符(\ n)。

#5


0  

for a pure shell solution without calling external program:

对于没有调用外部程序的纯shell解决方案:

NL=$'\n'    # define a variable to reference 'newline'

testVar=${testVar%$NL}    # removes trailing 'NL' from string

#6


0  

This removes all carriage returns from $testVar using shell parameter expansion and ANSI-C quoting (requires Bash):

这将使用shell参数扩展和ANSI-C引用(需要Bash)从$ testVar中删除所有回车:

testVar=${testVar//$'\r'}

#1


35  

yet another solution uses tr:

另一种解决方案使用tr:

echo $testVar | tr -d '\r'
cat myscript | tr -d '\r'

the option -d stands for delete.

选项-d代表删除。

#2


11  

You can use sed as follows:

您可以使用sed如下:

MY_NEW_VAR=$(echo $testVar | sed -e 's/\r//g')
echo ${MY_NEW_VAR} got it

By the way, try to do a dos2unix on your data file.

顺便说一句,尝试在数据文件上执行dos2unix。

#3


5  

use this command on your script file after copying it to Linux/Unix

将其复制到Linux / Unix后,在脚本文件上使用此命令

perl -pi -e 's/\r//' scriptfilename

#4


2  

Pipe to sed -e 's/[\r\n]//g' to remove both Carriage Returns (\r) and Line Feeds (\n) from each text line.

管道到sed -e's / [\ r \ n] // g'从每个文本行中删除回车符(\ r)和换行符(\ n)。

#5


0  

for a pure shell solution without calling external program:

对于没有调用外部程序的纯shell解决方案:

NL=$'\n'    # define a variable to reference 'newline'

testVar=${testVar%$NL}    # removes trailing 'NL' from string

#6


0  

This removes all carriage returns from $testVar using shell parameter expansion and ANSI-C quoting (requires Bash):

这将使用shell参数扩展和ANSI-C引用(需要Bash)从$ testVar中删除所有回车:

testVar=${testVar//$'\r'}