0

I'm new to bash.

I'm trying to write a script that will read data from a text find and declare some variables. In the example below we read from a tab delimited file "ab.txt" that looks like this:

a->AA

b->BB

Where -> denotes a tab.

I'm reading this data with this code:

#!/bin/bash
while read line
do
    tmp=(${line///})
    fieldName=${tmp[0]}

    case $fieldName in
    "a")
        a=${tmp[1]}
        ;;
    "b")
        b=${tmp[1]}
        ;;
    esac

done < "ab.txt"


echo "a:"
echo $a 

echo "b:"
echo $b

echo "concat a,b"
echo $a$b

echo "concat b,a"
echo $b$a

This gives me "a" and "b" nicely, but will not concatenate a and b! The output is this:

a:
AA
b:
BB
concat a,b
BB
concat b,a
AA

What am I doing wrong?

Adi Ro
  • 101
  • 3
  • 2
    `"This gives me "a" and "b" nicely"` Are you sure even that part is correct? According to the code you should only be getting `A` and `B` instead of `AA` and `BB`. When I ran your code I got that result and all concats were correct as well. Are you sure your input is correct? – kaylum Jan 08 '20 at 19:31
  • Agree with @kaylum, running your script gives me the desired output. – maulinglawns Jan 08 '20 at 19:32
  • 4
    The `AA` versus `A` is presumably a transcription error - however the apparent failure to concatenate is possibly another case of Windows (CRLF) line endings i.e. `AA\rBB\r` will appear as just `BB` – steeldriver Jan 08 '20 at 19:56
  • @steeldriver, that was it. I used dos2unix on the "ab.txt" file and now it works. Thanks! – Adi Ro Jan 09 '20 at 08:11
  • 1
    Rather than `read`ing the entire line and then splitting it into an array, I'd let `read` do the splitting: `while IFS=$\t\ read fieldName fieldValue` – Gordon Davisson Jan 09 '20 at 08:46

1 Answers1

0

@steedriver found the problem: In windows the end of lines have escape characters that linux doesn't have. I created the input text file ab.txt in windows, so linux read the extra characters into the a, b variables. My solution was to convert ab.text using dos2unix, that worked.

Adi Ro
  • 101
  • 3