0

I am writing a bash script which will read a CSV file and print the result in console with some string concatenation.

I am facing one issue with one string overwriting part of another when concatenating them in a bash script. Below is the whole code given and I am running it in Gitbash installed on my windows.

CSV File1 with two rows is given below

Apple,Cycle
Orange,Lamborgini

Script:

while IFS=, read -r x y
    do
            fruit=$x
            vehicle=$y
            echo "$y ran"
done < File1.csv

Actual Output:

ranle
ranborgini

Expected Output:

Cycle ran
Lamborgini ran
Priya Jain
  • 29
  • 3
  • It works fine. There's no issue with that script and it gives the expected output. Maybe try to `set -x` and see what is happening for you? – darnir Jan 22 '20 at 10:38
  • 3
    Works on my machine. I think it's the csv file you are using (it looks like a '\r' issue). – majodi Jan 22 '20 at 10:46

2 Answers2

2

I found that the output contains carriage return that needs to be removed. For the example above this could be done using the tr tool:

 while IFS=, read -r x y                                                                                          
 do
            fruit=$x
            vehicle=$(echo "$y" | tr -d '\r')
            echo "$y ran"
done < File1.csv

And now it is giving the expected output.

Priya Jain
  • 29
  • 3
1

On Windows file probably contains CLRF windows new lines with carriage return, not Unix ones.

Check this SO question and answers on options for converting new lines in file / line / string.

Oleg Russkin
  • 4,234
  • 1
  • 8
  • 20