shell

Overriding awk for Slight Convenience

In command line Bash language on Linux PC/server, this article introduces how to override awk to make it slightly more convenient. I previously wrote an article about overriding the <code>cd</code> command, and this has been quite convenient to use. I got a bit hooked on adding features to existing Linux and builtin commands.…

Shou Arisaka
2 min read
Oct 11, 2025

In command line Bash language on Linux PC/server, this article introduces how to override awk to make it slightly more convenient.

awk is convenient, isn’t it. I quite like awk too, and use it often. I’ve written several awk articles.

(shell) awkチートシート [外部コマンド実行] Bash awkで全てのカラムを出力するには

I previously wrote an article about overriding the cd command, and this has been quite convenient to use. Yeah, really convenient.

Bash cdコマンドでファイルを指定しても移動できるようにするだけ

So, I got a bit hooked on adding features to existing Linux and builtin commands.

But with awk… isn’t the syntax kind of tedious?

I quite often want to output the 2nd column, or the 3rd column, but writing awk '{print $2}' every time is tiresome, isn’t it.

Wouldn’t it be nice if you could do this:

$ echo 'hoge fuga' | awk '{print $2}'
fuga
$ echo 'hoge fuga' | awk 2
fuga

So I wrote it.

awk(){
    [[ "${1}" =~ ^[0-9]+$ ]] && /usr/bin/awk -v var="${1}" '{print $var}' || /usr/bin/awk "$@"
}

-v var="${1}" defines it as a variable to use in awk. With this, $2 becomes $2. Strictly speaking, strings in awk should be enclosed in "", so maybe it should have been '{print "$"var}', but since there are no bugs, it’s probably fine.

awk uses single quotes, so Bash variable expansion doesn’t work. So you have to take a roundabout way using the -v option.

[[ "${1}" =~ [0-9]+ ]] && /usr/bin/awk \'{print ${1}}\' || /usr/bin/awk "$@"  # => Error

[[ "${1}" =~ \d+ ]] && /usr/bin/awk '\''{print ${1}}'\'' || /usr/bin/awk "$@" # => Error

Update

Upgraded version.


awk(){

  : e.g. `# something | awk 2 `
  : e.g. `# something | awk nr2 `

  [[ "${1}" =~ ^[0-9]+$ ]] && { /usr/bin/awk -v var="${1}" '{print $var}' ; return 0 ; }
  [[ "${1}" =~ ^nr[0-9]+$ ]] && { /usr/bin/awk "NR==${1##+([a-z])}" ; return 0 ; }

  /usr/bin/awk "$@" && { return 0 ; }

}

NR and such can work with double quotes.

Share this article

Shou Arisaka Oct 11, 2025

🔗 Copy Links