4

I have this line of code for the shell:

ls -1 *.mp3| awk -v here="$(cygpath -w $PWD)" -v source="$source" '{print "File Name: "$0"\n"here"\n"source}'

Unfortunately it outputs:

File Name: Data 00053.mp3
C:UsersathenaWorkProject_10.MBT
Source: Converted from RAW

This line C:UsersathenaWorkProject_10.MBT Should be C:\Users\athena\Work\Project_10\00.MBT

I am now lost, a lot to learn here.

Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
Ken Ingram
  • 247
  • 2
  • 8

1 Answers1

8

That's an issue relating to how awk treats the value passed using -v. It interprets the backslashes in the passed string.

Instead, pass it through an environment variable:

here="$(cygpath -w "$PWD")" awk ... '{ print ... ENVIRON["here"] ... }'

ENVIRON is an associative array in awk that contains the values of the variables in the current environment, keyed by name.

Also related to your code:

Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
Kusalananda
  • 320,670
  • 36
  • 633
  • 936
  • It solved the issue for sure. – Ken Ingram Sep 19 '19 at 21:43
  • It doesn't work for multiple variables though. Any thoughts? – Ken Ingram Sep 20 '19 at 01:04
  • 1
    @KenIngram Did you try? `a=1 b=2 c=3 awk 'BEGIN { print ENVIRON["a"], ENVIRON["b"], ENVIRON["c"] }'`. You could obviously just `export` the variables instead of assigning them on the same command line as `awk` (but that would make them part of your script's environment too). – Kusalananda Sep 20 '19 at 05:27