2

I would like to add some awk commands to a bash script. The bash script takes a few inputs, and inputs are passed by $1, $2 and etc. When I call awk, I also want to use $1 to define a position in the table, how can I do it?

example.sh

#! /user/bin/bash
arg=$1
outfile=$2
awk -F, -OFS, -v '{$2="$arg"; print}' > outfile

In this script, $2 is resolved to $outfile. How can I avoid this?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
  • Just like you did since $1 and $2 in awk are totally unrelated to $1 and $2 in shell (no, $2 in the awk script does NOT resolve to $outfile) but see https://stackoverflow.com/q/19075671/1745001 for how to handle arg. – Ed Morton Oct 09 '19 at 17:53

1 Answers1

3

You have a few errors in your awk command.

The following will import $arg as the awk variable arg:

awk -F , -v OFS=, -v arg="$arg" '{ $2 = arg; print }' >"$outfile"

$2 can impossibly be interpreted as the second positional parameter here or in your code since it occurs in single quotes, and the shell does not expand single quoted variables.

OFS and arg (both are awk variables) are set with -v on the command line. You don't use -v to set OFS and you use -v in the wrong way in front of the actual awk code. This would have given you an error (which you don't mention). In fact -OFS, with GNU awk means "turn on optimisation and set the input field separator to the string S,".

Note that if $arg (the shell variable) contains backslashes that you need to preserve, then it's better to pass the value through the environment instead since these would otherwise be interpreted by awk:

arg="$arg" awk -F , -v OFS=, '{ $2 = ENVIRON["arg"]; print }' >"$outfile"

The output file is presumably supposed to be $outfile, not outfile.

Related:

Kusalananda
  • 333,661