2013-03-20 403 views
15

我是shell腳本的新手。我使用在Windows中創建的源命令來源文件,它有回車。在我追加一些字符的時候,它會一直到行的開頭。如何從shell腳本中的變量中刪除回車符和換行符

test.dat (which has carriage return at end) 
testVar=value123 

testScript.sh (sorces above file) 
source test.dat 
echo $testVar got it 

我得到的輸出是

got it23 

我怎樣才能把變量的 '\ r'。任何幫助都將非常可觀。

回答

4

使用的腳本文件這個命令將其複製到Linux/Unix的

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

由於一噸用於' perl'。我無法下載'dos2unix','tr'不能工作,什麼不可以!非常感謝! – 2018-01-26 16:55:52

10

後,您可以使用SED如下:

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

編輯

順便說一句試試在你的數據文件上做一個「dos2unix」。

32

另一個解決方案採用tr

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

選項-d代表delete

2

管到sed -e 's/[\r\n]//g'從對於純殼溶液每個文本行

+2

你不能使用sed來移除'\ n'。請參閱http://sed.sourceforge.net/sedfaq5.html#s5.10 – Bryan 2017-05-15 10:14:19

0

刪除這兩個回車返回(\r)和換行(\n),而不調用外部程序:

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

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