7

I want to create an alias for grep like this:

grep argX ~/myfile

where argX is a parameter and myfile is always the same. How can I do this?

Eliah Kagan
  • 117,780
fweigl
  • 384

3 Answers3

13

Aliases do not support positional parameters so you need to create a function (which you can put in ~/.bashrc). If you really want and alias, you could alias that function.

function grepMe(){
    grep "$1" ~/myfile
}

Then, if for some reason you want there to be an alias, you can make one for the function:

alias grepAlias="grepMe"
Eliah Kagan
  • 117,780
Rinzwind
  • 299,756
  • 3
    +1. Functions are the more generalized aliases suitable for this. And just to make the message clear: you don't have to create an alias; the function name will work fine in the command line. – mike3996 May 28 '13 at 14:41
5

Alias don't supports parameter but you can write a small script and name it i.e. "filegrep"

#!/bin/bash
grep "$1" /home/youruser/myfile

Copy the script to /usr/bin and you can run it with filegrep argX in the console.

Eliah Kagan
  • 117,780
prophecy201
  • 2,690
  • 16
  • 21
1

Here I found an alternative without using functions:

alias grepAlias='bash -xc '\''grep $0 ~/myfile'\'''

For example using Silver Searcher:

alias superlocate='bash -xc '\''ag -g $0 --hidden'\'' 2>/dev/null'
Pablo Bianchi
  • 15,657