How to alias an awk command

Solution 1:

There are a couple of problems with your alias.

First, the name of an alias is separated from its value by =, not white space.

Second, a ' cannot be nested within other quotes by escaping them with a \.

Your alias will work if written like this:

alias aprint='awk "{print \$1}"'

where the $ is preceded by a \ to prevent $1 from being expanded by the shell.

Solution 2:

Better than an alias, create a function for this kind of thing:

function aprint() { awk '{print $1}'; }

You can use it for example like this:

$ date
Fri Jan  3 08:09:23 CET 2014
$ date | aprint
Fri

You probably want to parameterize it too:

function aprint() { awk "{print \$${1:-1}}"; }

This way it will work with not only the 1st but any column easily:

$ date | aprint 2
Jan
$ date | aprint 6
2014

Using ${1:-1} the argument is optional, and by default it will use 1.

Solution 3:

alias somefunc='function _somefunc { ls -la ${1} |awk '\''{print $1}''\'; }; _somefunc'

Alias is fun like this. Not sure why you would setup an alias for awk per se, but if you do put it in a function and tokenize the input.

I usually use this when I want to tokenize some output and pass it on to something else, which is far more useful in aliases. This can work with a regular alias too, just be sure to use ; to demarcate the end of the alias before the single tick: e.g. alias other='ls -la |awk '\''{print $1}'\'';'