0

I have a file with contents like this:

FOO=#{Foo}

# may contain blank lines or lines with comments
BAR=#{Bar}

Now, I want to do some stuff with those that requires me to consider FOO and #{Foo} as separate entities. So I tried the following, to ensure that I get the data I want:

#!/bin/bash

while read -r line; do
  variable="${line%\=*}"
  toReplace="${line#*\=}"

  echo "$toReplace"
  printf "%s -> \$%s\n" "$toReplace" "$variable"
done < <(grep '=' myfile)

This outputs, to my great surprise, the following:

#{Foo}
 -> $FOO
#{Bar}
 -> $BAR

As you see, the toReplace part of the line is not printed, although it is apparently extracted correctly.

I also tried echo -n "$toReplace", which printed nothing.

Why is this? What can I do about it?

Tomas Aschan
  • 58,548
  • 56
  • 243
  • 402

1 Answers1

1

That's because the input file has MSWin line ends. The special character $'\r' gets interpreted as "goto line start", so -> $FOO overwrites the $toReplace part.

Run the input file through dos2unix or fromdos.

choroba
  • 231,213
  • 25
  • 204
  • 289
  • Thanks - would never have thought about this! Since this is a script that will run in a CI environment, where I want to install as few things as possible, I'll remove them with `sed 's/\r$//g'` instead of `dos2unix` or `fromdos`, but this does solve my problem. – Tomas Aschan Oct 11 '18 at 10:00