Home > OS >  How can I assign a string with quotes to a variable in bash, and use it as a pattern in awk?
How can I assign a string with quotes to a variable in bash, and use it as a pattern in awk?

Time:12-30

The command that I'm using is :

objects=shubham
awk -v myvar="$objects" '($0~myvar),/REPLACE/' a.txt

the a.txt file contains

other-unwanted-content-here
target(shubham)
hello('shubham')
abc
bcd
REPLACE
other-unwanted-content-here

My desired output is:

hello('shubham')
abc
bcd
REPLACE

...but I'm getting target(shubham) as well. How can I make hello('shubham') with the quotes be the place where awk starts matching?

CodePudding user response:

Two approaches, depending on what you want.

  • Keep objects defined the way it is, amend your awk variable's assignment

    objects=shubham
    awk -v myvar="^hello[(]'$objects'[)]\$" '($0~myvar),/REPLACE/' <<'EOF'
    

    See this running at https://ideone.com/Bto1hB

  • Change objects to match only the target line

    objects="^hello[(]'shubham'[)]\$"
    awk -v myvar="$objects" '($0~myvar),/REPLACE/' a.txt
    

    See this running at https://ideone.com/nF8MUl

Note that in either case, ~ in awk is a regex operator; since in most regex forms (including POSIX ERE) ( and ) are syntax, we had to change your string to be a regex that matches the desired line, instead of containing exactly that line itself. (Note that in both cases, the backslash before the $ in the regex is shell syntax, not regex syntax itself, necessary only because we're in double quotes; in single quotes those backslashes would need to be left out).

CodePudding user response:

Providing the patterns are unique to the relevant lines, combining the variable in your starting line pattern (using &&) with /hello/ should fix the extra line problem:

awk -v myvar="$objects" '($0~myvar && /hello/),/REPLACE/' a.txt

output:

hello('shubham')
abc
bcd
REPLACE

Tested using mawk 1.3.4 on Raspberry Pi 400

  • Related