I have problem with command awk in bash I want to find pattern with variable, but it doesn't work. Can you tell me what's wrong with this line?

awk -F" "  "/$PWD/ {print $1,$3}"  file.txt
  • double quote allow expansion of $1,$3 as well aw $PWD, try awk '/'$PWD'/ {print $1,$3}' – Archemar Mar 17 '15 at 14:11
  • it says synax error – applenic Mar 17 '15 at 14:13
  • what is $PWD value ? – Archemar Mar 17 '15 at 14:14
  • it's adress of directory – applenic Mar 17 '15 at 14:16
  • 2
    This is extremely similar to unix.stackexchange.com/a/190307/88983 where you received an answer that covers the reason why $PWD causes a syntax error. – dhag Mar 17 '15 at 14:40

Since you have been using double quotes, any $-variables will be expanded by bash before they reach awk. That's the first problem: { print $1, $3 } will expand to { print , }.

Next, the awk syntax you are trying to use is /<regular expression>/ { <action> }: the regular expression is not allowed to contain any unquoted slashes, but $PWD certainly contains some. That's the second issue.

You could try something like this instead:

"/${PWD//\//\\/}/ { print \$1, \$3 }"

This asks bash to replace any occurrences of / in $PWD with \/, and also escapes the $ signs of $1 and $3 so that bash leaves them intact.

  • it still says syntax error – applenic Mar 17 '15 at 14:40
  • Then it would be interesting for us to know exactly where your awk thinks there is an error. I tried with GNU awk 4.0.1, successfully. – dhag Mar 17 '15 at 14:42
  • 1
    The syntax error is because you forgot a slash: ${PWD//\//\/} should be ${PWD//\//\\/}. I fixed it. – terdon Mar 17 '15 at 15:42
  • I tested the actual code that I posted, and the extra backslash should make no difference in this case (because it is within double quotes and does not precede a character with special meaning). Thanks for the edit anyway; doubling the backslash is probably less confusing. – dhag Mar 17 '15 at 15:48

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.