Awk - Unterminated Regex

I am writing a shell script which needs to pull values out of a text file which looks like this:

app.full.name /warfilelocation/ warfilename

My shell script will be iterating over a list of application names and pulling out either the location or name using AWK. I have tested doing this on the command line using the following: awk "\$1 ~/ { print $2 }" applications.txt

which returns what I would expect however when i put this in a shell script I start having issues.

I have a function that looks like this:

function get_location() {
        local application=$1
        awk "\$1 ~/^$application/ { print \$2 }"  applications.txt 
}

But when i call this function i get the following error:

awk: $1 ~/^app.full.name
awk:      ^ unterminated regexp
awk: cmd. line:1: app.full.name
awk: cmd. line:1:         ^ syntax error
awk: cmd. line:2:  { print $2 }
awk: cmd. line:2:    ^ syntax error

Does anyone have any ideas what I am doing wrong here. I presume I am not escaping the variable correct but no matter what i try it doesnt seem to work.

Thanks in advance

1

4 Answers

Use this approach to make awk recognize shell variables:

awk -v "v1=$VAR1" -v "v2=$VAR2" '{print v1, v2}' input_file

Update

$ cat input
tinky-winky
dipsy
laa-laa
noo-noo
po

$ teletubby='po'

$ awk -v "regexp=$teletubby" '$0 ~ regexp' input
po

Note that anything could go into the shell-variable, even a full-blown regexp, e.g ^d.*y. Just make sure to use single-quotes to prevent the shell from doing any expansion.

5

The error messages seem to indicate that there is a stray newline at the end of $application, which gives the "line 2" error messages.

2

see this: using awk match() function

kent$  app=app.ful
kent$  echo "app.full.name /warfilelocation/ warfilename"|awk -v a=$app '{if(match($1,a))print $2}' 
/warfilelocation/

It's hard to tell without knowing exactly the value of $application, but it seems like you have a strange character in $application, such as a " or a / or something like that.

$ export application=foo/bar
$ awk "\$1 ~/^$application/ { print \$1 }"
gawk: cmd. line:1: $1 ~/^foo/bar/ { print $1 }
gawk: cmd. line:1:                ^ parse error

I would look at the exact value that you have in $application, and if it contains a /, escape it.

One way to do this would be to use:

$ export application=`echo foo/bar | sed -e 's;/;\\\\/;g'`
$ awk "\$1 ~/^$application/ { print \$1 }"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.

Share this article
Twitter Facebook Pinterest