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
2
  • 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? Commented Jan 22, 2020 at 10:38
  • 3
    Works on my machine. I think it's the csv file you are using (it looks like a '\r' issue). Commented Jan 22, 2020 at 10:46

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.