0

In a bash script, I need to do this:

cat<<EOF> ins.exe
grep 'pattern' file | awk '{print $2}' > results
EOF

The problem is that $2 is interpreted as a variable and the file ins.exe ends up containing "grep 'pattern' file | awk '{print }' > results", without the $2.

I've tried using

echo "grep 'pattern' file | awk '{print $2}' > results" >> ins.exe

But it's the same problem.

How can I fix this?

1
  • 1
    Have you tried awk '{print \$2}'? Commented Dec 13, 2016 at 10:34

1 Answer 1

3

Just escape the $:

cat<<EOF> ins.exe
awk '/pattern/ { print \$2 }' file > results
EOF

No need to pipe grep to awk, by the way.

With bash, you have another option as well, which is to use <<'EOF'. This means that no expansions will occur within the string.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, nice answer!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.