简体   繁体   English

Linux Shell:如何为find命令的别名赋予参数?

[英]Linux shell: How to give parameter to alias of find command?

Eg, I wish to lookup current directory(exclude ./bin) for all files named "Makefile", as argument and grep "library", like below: 例如,我希望查找所有名为“ Makefile”的文件的当前目录(不包括./bin),作为参数和grep“ library”,如下所示:

find . ! -path "./build" -name "*Makefile"|xargs grep library

I don't with to type all these each time, I just want to make an "alias" with 2 parameters, like: 我不必每次都键入所有这些内容,我只想使用2个参数制作一个“别名”,例如:

myfind "*Makefile" "library"

myfind's find parameter is fo "find" command as "name",the second parameter for "grep" command, also I wish the asterisk "*" can be passes as part of parameter, without being parsed. myfind的find参数是“ find”命令中的“ name”,第二个参数是“ grep”命令,我也希望星号“ *”可以作为参数的一部分传递,而不进行解析。

How to write such an alias? 如何写这样的别名?

使用功能:

myfind() { find . ! -path "./build" -name "$1"|xargs grep "$2"; }

You can't do that with an alias. 您不能使用别名来做到这一点。 You could write a small script eg 您可以编写一个小脚本,例如

#!/bin/bash
find . ! -path "./build" -name "$1"|xargs grep $2

Save it as myfind somewhere on your path and make sure to remove the alias. 将其另存为myfind ,位于路径上的某个位置,并确保删除别名。

You used the tag linux, so I assume that you are using GNU grep. 您使用了标记linux,所以我假设您正在使用GNU grep。 GNU grep (at least grep (GNU grep) 2.25 ) supports the following options, which make your task very easy. GNU grep(至少是grep (GNU grep) 2.25 )支持以下选项,这使您的工作非常轻松。 Let me cite from grep --help : 让我从grep --help引用:

 -r, --recursive           like --directories=recurse
 --include=FILE_PATTERN  search only files that match FILE_PATTERN
 --exclude=FILE_PATTERN  skip files and directories matching FILE_PATTERN
 --exclude-from=FILE   skip files matching any file pattern from FILE
 --exclude-dir=PATTERN  directories that match PATTERN will be skipped.

So your task can be accomplisehd by: 因此,您的任务可以通过以下方式完成:

grep -r --include=Makefile --exclude-dir=build library

Of course you can create a shell script or function to further simplify that. 当然,您可以创建一个shell脚本或函数来进一步简化它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM