3

I just came across a gotcha in awk, and I would like to know if anyone can explain to me why this happens.

The following 2 lines behave differently if I run:

# grep -Rl BASE_DIR --exclude-dir=.svn * | awk -F "/" '{print $1}'

I get (as expected) just the first directory of the path to files containing BASE_DIR.

However, if I run it like this:

# grep -Rl BASE_DIR --exclude-dir=.svn * | awk -F="/" "{print $1}"

EDIT:

-F="/" and -F "/" don't make a difference on my tests. the second command has been updated to show this

as suggested by glenn jackman on the answer I changed the command to:

# grep -Rl BASE_DIR --exclude-dir=.svn * | awk -F "/" "{print $1}"

and got the exact same flawed result

End of EDIT

I get the full path to files containing BASE_DIR, I tried escaping the program text so it would be "{print \$1}" in case this was the issue, but I got the same results.

Can anybody enlighten me as to what the problem is here?

2

In the first example, you're doing: awk -F "/"
In the next example, you're doing: awk -F="/"

So the field separator is different: you're using the two character string =/ as the field separator


Ah, I don't know why I didn't see this before: you're using the wrong quotes:

# grep -Rl BASE_DIR --exclude-dir=.svn * | awk -F "/" "{print $1}"
------------------------------------------------------^

The double quotes around the awk program means that the shell will substitute the variable $1 before handing the program to awk. Most likely, in the shell, $1 is empty, so awk sees this: {print }

Use single quotes instead.

  • nope, that's not it, I just changed it to test and still failed – rantsh Mar 27 '13 at 16:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.