0

I have a file like this (where xxxxn = any random string):

xxxx1
xxxx2
xxxx3
xxxx4
END
xxxx5
xxxx6
xxxx7
END
xxxx8
...

I want to match between a shell variable and the next END. Say the shell variable equals xxxx2, I would like:

xxxx3
xxxx4

I think awk is probably the tool for the job but I'm open to other commands.

I have got it working if I hard code it (with xxxx2 again) like so:

awk '/xxxx2/{flag=1;next}/^END/{flag=0}flag' file

But I would like it to reference a shell variable and the symbols to be escaped. I tried:

awk -v var="$my_var" '/~var/{flag=1;next}/^END/{flag=0}flag' file

(After reading this https://stackoverflow.com/a/39384347/11633601) But that outputs nothing.

Thanks.

GGG
  • 295
  • 1
  • 9

2 Answers2

1

Var should be declared with -v for awk How do I use shell variables in an awk script?

So this should do:

my_var="xxxx2"
awk -v var="$my_var" '/END/ {exit} f; $0==var {f=1}' file
xxxx3
xxxx4

You could set f=0 to stop printing, but exit is better since it stops processing data.

awk -v var="$my_var" '/END/ {f=0} f; $0==var {f=1}' file
Jotne
  • 40,548
  • 12
  • 51
  • 55
  • I suggest to replace `f=1` with `f=1; next` to remove `xxxx2` from output. – Cyrus Aug 19 '19 at 19:34
  • @Cyrus Did forget that `xxxx2` should not be printed. Its better to swap around test, compare to use `next` – Jotne Aug 19 '19 at 19:37
0

You can replace the hard-coded xxxx2 with the shell variable, but outside of the single quotes, and double it in case it contains white spaces:

awk /"$my_var"'/{flag=1;next}/^END$/{flag=0}flag' file

Also, you should consider using the ed command instead as pointed out by this answer so it would be much more readable:

echo /"$my_var"'/+1,/^END$/-1p' | ed -s file -
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • Lets say line 2 in OPs post is `\xxxx2`. Then you set `my_var="\xxxx2"`. Then you code will fail due to your way to use variable in `awk`. You could also put code in your variable and make it execute in your `awk` code. (code injection) – Jotne Aug 19 '19 at 19:50