如何在xargs中使用别名命令?

时间:2009-06-11 05:23:45

标签: linux tcsh xargs

我的.aliases中有以下别名:

alias gi grep -i

我希望在名称中包含字符串foo的所有文件中不区分大小写bar

find -name \*bar\* | xargs gi foo

这就是我得到的:

xargs: gi: No such file or directory

有没有办法在xargs中使用别名,或者我是否必须使用完整版本:

   find -name \*bar\* | xargs grep -i foo

注意:这是一个简单的例子。除了gi我还有一些非常复杂的别名,我无法轻易手动扩展。

修改:我使用了tcsh,因此请指明答案是否是特定于shell的。

7 个答案:

答案 0 :(得分:28)

别名是特定于shell的 - 在这种情况下,很可能是特定于bash的。要执行别名,您需要执行bash,但只为交互式shell加载别名(更准确地说,只有交互式shell才会读取.bashrc。)

bash -i 运行交互式shell(和源.bashrc)。 bash -c cmd 运行 cmd

把它们放在一起: bash -ic cmd 在交互式shell中运行 cmd ,其中 cmd 可以是在其中定义的bash函数/别名你的.bashrc

find -name \*bar\* | xargs bash -ic gi foo

应该做你想做的事。

编辑:我发现您已将问题标记为“tcsh”,因此特定于bash的解决方案不适用。使用tcsh,您不需要-i,因为它似乎会读取.tcshrc,除非您提供-f

试试这个:

find -name \*bar\* | xargs tcsh -c gi foo

它适用于我的基本测试。

答案 1 :(得分:7)

将“gi”改为剧本

例如,在/home/$USER/bin/gi中:

#!/bin/sh
exec /bin/grep -i "$@"

不要忘记标记文件的可执行文件。

答案 2 :(得分:6)

建议here是为了避免xargs并使用“while read”循环而不是xargs:

find -name \*bar\* | while read file; do gi foo "$file"; done

请参阅上面链接中的已接受答案,以了解处理文件名中的空格或换行符的改进。

答案 3 :(得分:5)

在bash中,此解决方案非常适合我:
https://unix.stackexchange.com/a/244516/365245

问题

[~]: alias grep='grep -i'
[~]: find -maxdepth 1 -name ".bashrc" | xargs grep name      # grep alias not expanded
[~]: ### no matches found ###

解决方案

[~]: alias xargs='xargs ' # create an xargs alias with trailing space
[~]: find -maxdepth 1 -name ".bashrc" | xargs grep name     # grep alias gets expanded
# Name     : .bashrc

为什么起作用

[~]: man alias  
alias: alias [-p] [name[=value] ... ]  
(snip)  
A trailing space in VALUE causes the next word to be checked for
alias substitution when the alias is expanded.

答案 4 :(得分:0)

对于tcsh(没有功能),您可以使用:

gi foo `find -name "*bar*"`

对于bash / ksh / sh,您可以在shell中创建一个函数。

   function foobar 
   {
      gi $1 `find . -type f -name "*"$2"*"`
   }

   foobar foo bar

请记住,在shell中使用反引号比从多个视角使用xargs更有利。将函数放在.bashrc中。

答案 5 :(得分:0)

使用Bash你也可以指定传递给你的别名(或函数)的args数量,如下所示:

alias myFuncOrAlias='echo'  # alias defined in your ~/.bashrc, ~/.profile, ...
echo arg1 arg2 | xargs -n 1 bash -cil 'myFuncOrAlias "$1"' arg0

(应该以类似的方式为tcsh工作)

# alias definition in ~/.tcshrc
echo arg1 arg2 | xargs -n 1 tcsh -cim 'myFuncOrAlias "$1"' arg0  # untested

答案 6 :(得分:0)

最简单的解决方案是扩展别名内联。但这仅对csh / tcsh有效。

find -name \*bar\* | xargs `alias gi` foo

对于bash来说,它会比较棘手,虽然不那么方便,但仍然可能有用:

find -name \*bar\* | xargs `alias gi | cut -d "'" -f2` foo
相关问题