0

I'm trying to stick the text output of a linux command into a single cell of a csv file. No matter how I try to escape quotes, the newline characters do not seem to be registered by the csv file.

For example if the output of one of these commands is:

155 C T
2518 T C

It is being printed within the csv cell as:

155 C T 2518 T C
for filename in "$1"/*JGI*.vcf; do
    counter=$((counter + 1))

    depth_score="$(samtools depth "${filename%.*}.bam" | python depth.py)"
    variant_array="$(bcftools query -f '%POS %REF %ALT\n' "$filename")"
    column_name="$(basename "$filename")"

    echo "$counter/$total_colonies" # echo current/total
    echo "$variant_array"
    echo ""$variant_array""
    echo "$column_name, "$variant_array", $depth_score" >> output.csv
done

Here is the for loop that's giving me some errors.

The result of the $variant_array is the problem.

I have two print logs above where I write to the output.csv to see what's going on.

"$variant_array" yields the desired behavior, but for some reason when I echo that within another set of quotes to write it to the csv file, it ignores the newlines...

1
  • 1
    Add a shebang and then paste your script there: shellcheck.net Commented May 24, 2019 at 4:38

2 Answers 2

2

Quotes do not escape this way... So perhaps the following will work for you?

echo '"'"$variant_array"'"'
echo "$column_name", '"'"$variant_array"'"', "$depth_score" >> output.csv

Here is another form of escaping quotes:

echo \""$variant_array"\"
echo "$column_name", \""$variant_array"\", "$depth_score" >> output.csv

Here is another idea:

echo "\"$variant_array\""
echo "$column_name, \"$variant_array\", $depth_score" >> output.csv
Sign up to request clarification or add additional context in comments.

3 Comments

Good point. In a CSV file, the OP probably does want double-quotes to appear in the output.
Possibly simpler: echo "\"$variant_array\""
Both the second two were perfect solutions. Thanks!
0

The problem is that $variant_array is not "within another set of quotes." It is entirely unquoted.

Replace:

echo "$column_name, "$variant_array", $depth_score" >> output.csv

with:

echo "$column_name", "$variant_array", "$depth_score" >> output.csv

or, simpler still:

echo "$column_name, $variant_array, $depth_score" >> output.csv

1 Comment

It happens to all of us at one time or another.

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.