1

I want to print part of the content of a .csv file in another file if there is a match with some condition:

The csv content is like this

abc test;ABCtest.it
xyz test;XYZtest.com

I read the content in a variable and I grep it for some string

csvContent=$(<$file.csv)

csvRow="$(echo "$csvContent" | grep -i "abc test")"

IFS=';' read -a array <<< "$csvRow"
name="${array[0]}"
url="${array[1]}"

echo -ne "\n$url,$name" >> "$outputDir/$fileName"

But the output file doesn't contain the url part

If I try this

echo $url

it's printed on the terminal!

I've tried also with printf and with an hardcoded filename but nothing!

printf '%s %s\n' "$url" "$name"  >> test.txt

It seems that when I try to concatenate another thing (a variable or a string) after the variable $url some part of this is deleted or overwritten into the output file

For example if I try with this

printf '%s %s\n' "$url" "pp"  >> test.txt

What I get with a simple cat test.txt is this :

 pptest.it

it is as if part of it was overwritten with a starting empty space

the content of the variable $url must be ABCTest.it

it's very strange

  • 2
    Does your csv file have windows line endings? If yes, the the value of $url will be ABCtest.it\r and when you use echo -e that carriage return will send the cursor back to the start of the line, and the comma and the name will overwrite the url. – glenn jackman Apr 1 '15 at 18:17
  • Bingo! thank you very much ! I used this code to remove carriage return | tr -d '\r' and now works! Thank you – GabryRome Apr 1 '15 at 19:42
  • You've found your answer already, but your script looks overly complex. If that's not deliberately coded that way, I want to ask why you have not just done something like csvRow=$(grep -i "abc test" "$file.csv"). – Janis Apr 1 '15 at 23:27
2

You have carriage returns at the ends of the lines in your file.csv file, and so they get read in to your url variable.  And so, when you write it out, the URL data is followed by a carriage return and overwritten by subsequent data.

0

If it's a standard csv file like this

col1,col2,abc test;ABCtest.it,col4,col5
col1,col2,xyz test;XYZtest.com,col4,col5

You can use cut or probably awk.

grep -i "abc test" <filename.csv> | cut -f3 -d',' | cut -f2 -d';'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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