Search code examples
bashshellawkquoting

awk/bash quoting: print \ in echo


We need to print out

targetID="123"

AssayID="456",

awk -F\", 'BEGIN{FS=",";OFS=",";} {print $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$13,$14,$15,$16,$17,$18,$19,$20,$12}' VrtAssay_123_target_456_assay_Detail2.csv > VrtAssay_123_target_456_assay_Detail2_reorder.csv

A. We try:

printf "awk -F"\""," 'BEGIN{FS=\",\";OFS=\",\";} {print \$1,\$2,\$3,\$4,\$5,\$6,\$7,\$8,\$9,\$10,\$11,\$20,\$12,\$13,\$14,\$15,\$16,\$17,\$18,\$19}' VrtAssay_${TargetIDs}_target_${AssayID}_assay_Detail2_average.csv > VrtAssay_${TargetIDs}_target_${AssayID}_assay_Detail3.csv"

B. or echo

echo "awk -F"\"", 'BEGIN{FS=\",\";OFS=\",\";} {print \$1,\$2,\$3,\$4,\$5,\$6,\$7,\$8,\$9,\$10,\$11,\$20,\$12,\$13,\$14,\$15,\$16,\$17,\$18,\$19}' VrtAssay_${TargetIDs}_target_${AssayID}_assay_Detail2_average.csv > VrtAssay_${TargetIDs}_target_${AssayID}_assay_Detail3.csv"

Both give (\ is gone)

awk -F", 'BEGIN{FS=",";OFS=",";} {print $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$13,$14,$15,$16,$17,$18,$19,$20,$12}' VrtAssay_123_target_456_assay_Detail2.csv > VrtAssay_123_target_456_assay_Detail2_reorder.csv

C. If we try

printf "awk -F\\", 'BEGIN{FS=\",\";OFS=\",\";} {print \$1,\$2,\$3,\$4,\$5,\$6,\$7,\$8,\$9,\$10,\$11,\$20,\$12,\$13,\$14,\$15,\$16,\$17,\$18,\$19}' VrtAssay_${TargetIDs}_target_${AssayID}_assay_Detail2_average.csv > VrtAssay_${TargetIDs}_target_${AssayID}_assay_Detail3.csv" 

These will give an error message of

Unmatched ".

D. If we try

echo "awk -F\\", 'BEGIN{FS=\",\";OFS=\",\";} {print \$1,\$2,\$3,\$4,\$5,\$6,\$7,\$8,\$9,\$10,\$11,\$20,\$12,\$13,\$14,\$15,\$16,\$17,\$18,\$19}' VrtAssay_${TargetIDs}_target_${AssayID}_assay_Detail2_average.csv > VrtAssay_${TargetIDs}_target_${AssayID}_assay_Detail3.csv"

This gives us

Unmatched ".

Wonder any guru could kindly offer some solutions?


Solution

  • Any of these work, you just need to make sure that everything's escaped properly:

     $ echo 'awk -F\",'
     $ echo awk -F\\\",
     $ echo "awk -F\\\","
    

    The shell's parsing rules are basically:

    • Inside 'single quotes', everything except for single quotes is interpreted literally; to include a literal single quote, you need to close the single quote and then use double quotes to get that.
    • Inside "double quotes", double quotes and backslashes must be escaped with a backslash. So, a literal double quote is \", a literal backslash is \\, and a literal backslash and double quote are \\\". If you just write \\", that's a literal backslash followed by a closing quote.