Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
add comment

3 Answers

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.

share|improve this answer
add comment

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.

share|improve this answer
add comment

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

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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