3

I have the following AWK command which works well.

awk -v RS="\n+?[$]{4}\n+?" '/HMDB0000008/' test.xt

However what I want is to be able to call it from the command line and pass an argument so that it can find what I want.

For example, something like this:

awk -f var=HMDB0000008 RS="\n+?[$]{4}\n+?" '/$var/' test.txt

However this does not seem to work. Can you tell me what would be the best way?

Thank you

αғsнιη
  • 40,939
  • 15
  • 71
  • 114
js352
  • 133
  • 2
  • 2
    See [Pass shell variable as a /pattern/ to awk](https://unix.stackexchange.com/questions/120788/pass-shell-variable-as-a-pattern-to-awk) – steeldriver Nov 25 '20 at 17:55
  • 5
    Does this answer your question? [Pass shell variable as a /pattern/ to awk](https://unix.stackexchange.com/questions/120788/pass-shell-variable-as-a-pattern-to-awk) – thanasisp Nov 25 '20 at 18:13
  • Why [get an answer on SO](https://stackoverflow.com/a/65009434/1745001) and then immediately ask a question about that answer here on SE? – Ed Morton Nov 25 '20 at 20:28

1 Answers1

5

awk doesn't use $ to expand variables, additionally they are passed with the -v option not -f. Also strings within /.../ will be treated as a regex pattern so you need to use the ~ pattern match operator against the entire line ($0):

awk -v var=HMDB0000008 -v RS="\n+?[$]{4}\n+?" '$0 ~ var' test.txt
jesse_b
  • 35,934
  • 12
  • 91
  • 140
  • 2
    Also awk regexps don't have perl's `+?` operator. Even if it was supported, it wouldn't make much sense here, the first one would make no difference compared the `+` and the second is superflous as a non-greedy `\n+?` followed by nothing is the same as just `\n`. (using a regexp as RS is also not standard/portable) – Stéphane Chazelas Nov 25 '20 at 19:19
  • 1
    See also `index()` to find substrings. – Stéphane Chazelas Nov 25 '20 at 19:20