1

I am building a generic script which will be re-used from several other scripts. For each case, I need to extract Nth field in the generic script; in some cases the double quotes should be removed from that script. The field delimiter also varies from case to case.

Ideally I would like to simply pass an entire awk statement to the generic script, like this:

script1.sh:

 generic_script.sh "{print $1}"

script2.sh:

 generic_script.sh "BEGIN {FS=","} {gsub(/"/, "", $1);  print $1}"

generic_script.sh

 awk_expression="$1"
 awk '$awk_expression' file_to_process.txt

(I intentionally omitted escaping of " and $ in script2.sh for the sake of readibility of this question).

What is "proper enough" way to make such a generic script, and also to provide right arguments in these two scripts?

Both awk and gawk are available for me; I'm on MacOS HighSierra 10.13.6.

1
  • It's not clear what your problem is. Both awk "$1" file or a=$1; awk "$a" file in generic_script.sh should be fine. Read about the difference between ' and " quoting -- you shouldn't escape anything in script2.sh but to quote using ': generic_script 'BEGIN{ ... $1 ...}'.
    – user313992
    Sep 27, 2018 at 19:18

1 Answer 1

2

This should cover it.

$ cat generic_script.sh
#!/bin/bash
awk_expression="$1"
awk "$awk_expression" file_to_process.txt
$ cat file_to_process.txt
"foo","bar"
$ ./generic_script.sh '{ print $1 }'
"foo","bar"
$ ./generic_script.sh 'BEGIN {FS=","} {gsub(/"/, "", $1);  print $1}'
foo
$
3
  • The problem is that I also need to support script2.sh, which requires to set input field separator, and to remove quotes around the selected field :-) Sep 27, 2018 at 19:46
  • Yes, works for that, example added.
    – steve
    Sep 27, 2018 at 19:52
  • 1
    Thanks, it works! Looks like I messed up something with how quoting works in sh. Sep 27, 2018 at 22:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .