0

I have a script where I run a pipeline and the last command is awk, and I'd like to place a command line argument in that part.

OUTPUT=`sort -t' ' -k +6,6 -k +7,7 | awk '{print "        $1"$0}'`

I'd like the $1 in the end to be the argument that I received when I ran the script, instead of being treated as a dollar-one string and being parsed by the awk command.

Is there an elegant solution for that, or should I just pass on the awk part and then iterate over every line of OUTPUT and add the spaces and arguments I wanted to add with awk?

GabeL
  • 655
  • 9
  • 24
  • 1
    It's a good idea to get into the habit of using `$(command)` instead of backticks, btw. See https://mywiki.wooledge.org/BashFAQ/082 and https://github.com/koalaman/shellcheck/wiki/SC2006 for details. – Shawn Sep 04 '19 at 13:48
  • @Shawn Didn't even know that's possible. Thanks for the tip. – GabeL Sep 04 '19 at 14:56

2 Answers2

1

Use -v.

$: set -- foo # set $1 for this example
$: awk -v arg1=$1 '{print "        ", arg1, $0}' < someInput

Or without the spaces (more like you had),

$: awk -v arg1=$1 '{print "        " arg1 $0}' < someInput

c.f. the (in this case GNU) awk user manual

Paul Hodges
  • 13,382
  • 1
  • 17
  • 36
-1

The simplest solution is to use the "unquote requote" trick to move the $1 outside of the single quotes:

OUTPUT=`sort -t' ' -k +6,6 -k +7,7 | awk '{print "        '$1'"$0}'`

You're also probably going to want to unset IFS before that command in your script to prevent "Word Splitting", if you're not already doing it. Otherwise bash is going to "edit out" all extra whitespace, including the newlines:

IFS=
OUTPUT=`sort -t' ' -k +6,6 -k +7,7 | awk '{print "        '$1'"$0}'`
Jeff Y
  • 2,437
  • 1
  • 11
  • 18
  • This is fragile, as it depends on `$1` not containing any characters that will change how the `awk` script is parsed. – chepner Sep 04 '19 at 14:47
  • @chepner It's still inside double quotes within awk, so I don't think it's fragile to anything except an embedded double-quote, which I doubt is likely. But point taken. – Jeff Y Sep 04 '19 at 14:54