3

I want simplify awk command for common usage so instead of writing awk '{print "rm -r"$4 }' each time I want to write myawk "rm -r"$4. I've tried to write such function

myawk() { awk '{ print $1 }' } and it dosn't work..

How can I write function such that in Ubuntu?

3 Answers 3

4

To pass a string from a shell script to an embedded awk script, use an awk variable and the -v argument.

myawk () {
  awk -v mystring="$1" '{ print mystring }'
}

Another possibility is to put the string in an environment variable and access it through the ENVIRON array.

1

Try using double quotes instead of single. http://www.gnu.org/s/bash/manual/html_node/Double-Quotes.html

Or writing it this way:

myawk () { awk '{print '"$1"' }'; }

But I can see a lot of bad side effects with trying to include raw user strings. For example:

myawk '"hello"; system("echo there")"

This would get evaluated as awk '{print "hello"; system("echo there") }', which may display "hello" and "there; but more malicious commands could be sent if not escaped properly.

-1

What about adding alias awk="awk '{print $1 }'" to your .bashrc file?

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .