2

I want to use my awk shortcut as a function, so that I can pass the column number which then prints me the output. My aliases are:

alias A="| awk '{print \$1}'
alias G="| grep -i'

Instad of typing:

ps -ef | grep mysql | awk 'print $2'

I want to be able to type this:

ps -ef G mysql A 2

Any suggestions?

4
  • 4
    For a completely different approach, try pgrep -f mysql (assuming pgrep is available).
    – jw013
    Commented Jul 27, 2012 at 17:04
  • nice tool thx!!
    – DannyRe
    Commented Jul 27, 2012 at 17:13
  • Indeed. And for arbitrary fields, ps -o <field> $(pgrep mysql).
    – Mikel
    Commented Jul 27, 2012 at 17:22
  • 1
    or ps h -o %p -C mysqld if you want the PIDs of a particular named process (-C is exact match, not search pattern or regexp). You can have multiple -C args, e.g. ps h -o %p -C mysqld -C mysql to get client and server processes.
    – cas
    Commented Jul 27, 2012 at 21:06

2 Answers 2

5

I don't think it's possible. Basically, aliases can't take arguments ($1), and functions can't do macro expansion (|).

The closest options I can think of:

in bash or zsh

C() { col=$1; shift; eval "awkcmd='{ print \$$col }'"; echo "$awkcmd"; "$@" | awk "$awkcmd"; }

C 2 ps -ef G mysql

in zsh

alias -g F="| tr -s '[[:space:]]' | cut -d ' ' -f"

ps -ef G mysql F 2
0

Putting pipes into aliases is awkward. Instead, create a shell function that you can pipe things to:

G () {
    grep -i "$@"
}

A () {
    awk -v col="$1" '{ print $col }'
}

Then,

ps -ef | G mysql | A 2

But this particular pipeline would, on a Linux system, be more or less the same as

pgrep mysql

You must log in to answer this question.

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