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?

1
  • Can you post the output of hexdump -c myfile and file myfile
    – Inian
    Commented Oct 11, 2018 at 9:51

1 Answer 1

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.

1
  • 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. Commented Oct 11, 2018 at 10:00

Not the answer you're looking for? Browse other questions tagged or ask your own question.