57

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.

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

testVar=value123

testScript.sh (sources above file):

source test.dat
echo $testVar got it

The output I get is

got it23

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

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Lolly
  • 34,250
  • 42
  • 115
  • 150
  • When you've written a Linux script in Windows, you need to convert the whole file so that all of the carriage returns are removed before running it, otherwise you will run into all sorts of problems. Attempting to replace individual carriage returns might fix some problems, but others will appear. For me it was often with messages about lines that were truncated. Thus, it is best to convert the whole file using a program like `dos2unix`. – Dave F Apr 07 '21 at 21:49
  • Its an old one ofcourse, but this oneliner should do too. `echo ${testVar%'\r'}` – AP22 Jun 30 '21 at 02:17

6 Answers6

92

yet another solution uses tr:

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

the option -d stands for delete.

Nik O'Lai
  • 3,586
  • 1
  • 15
  • 17
32

You can use sed as follows:

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.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Xavier S.
  • 1,147
  • 13
  • 33
25

Because the file you source ends lines with carriage returns, the contents of $testVar are likely to look like this:

$ printf '%q\n' "$testVar"
$'value123\r'

(The first line's $ is the shell prompt; the second line's $ is from the %q formatting string, indicating $'' quoting.)

To get rid of the carriage return, you can use shell parameter expansion and ANSI-C quoting (requires Bash):

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

Which should result in

$ printf '%q\n' "$testVar"
value123
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
8

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

perl -pi -e 's/\r//' scriptfilename
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
Vorsprung
  • 32,923
  • 5
  • 39
  • 63
6

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

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
mcandre
  • 22,868
  • 20
  • 88
  • 147
  • 4
    You cannot remove `\n` using sed like that. See http://sed.sourceforge.net/sedfaq5.html#s5.10 – Bryan May 15 '17 at 10:14
5

for a pure shell solution without calling external program:

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

testVar=${testVar%$NL}    # removes trailing 'NL' from string
t j
  • 7,026
  • 12
  • 46
  • 66
The O.G. X
  • 51
  • 1
  • 1