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

Nat*_*man 26 linux tcsh xargs

我的.aliases中有以下别名:

alias gi grep -i
Run Code Online (Sandbox Code Playgroud)

我想foo在所有bar名称中包含字符串的文件中查找不区分大小写的内容:

find -name \*bar\* | xargs gi foo
Run Code Online (Sandbox Code Playgroud)

这就是我得到的:

xargs: gi: No such file or directory
Run Code Online (Sandbox Code Playgroud)

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

   find -name \*bar\* | xargs grep -i foo
Run Code Online (Sandbox Code Playgroud)

注意: 这是一个简单的例子.此外,gi我有一些非常复杂的别名,我不能轻易手动扩展.

编辑: 我用过tcsh,所以请指明答案是否是特定于shell的.

cam*_*amh 30

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

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

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

find -name \*bar\* | xargs bash -ic gi foo
Run Code Online (Sandbox Code Playgroud)

应该做你想做的事.

编辑:我看到你已将问题标记为"tcsh",因此特定于bash的解决方案不适用.使用tcsh,你不需要-i,因为它似乎读取.tcshrc除非你给-f.

试试这个:

find -name \*bar\* | xargs tcsh -c gi foo
Run Code Online (Sandbox Code Playgroud)

它适用于我的基本测试.


小智 7

将"gi"改为脚本

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

#!/bin/sh
exec /bin/grep -i "$@"
Run Code Online (Sandbox Code Playgroud)

不要忘记标记文件可执行文件.


Pet*_*aat 6

这里的建议是避免使用xargs并使用"while read"循环而不是xargs:

find -name \*bar\* | while read file; do gi foo "$file"; done
Run Code Online (Sandbox Code Playgroud)

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


小智 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 ###
Run Code Online (Sandbox Code Playgroud)

解决方案

[~]: alias xargs='xargs ' # create an xargs alias with trailing space
[~]: find -maxdepth 1 -name ".bashrc" | xargs grep name     # grep alias gets expanded
# Name     : .bashrc
Run Code Online (Sandbox Code Playgroud)

为什么有效

[~]: 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.
Run Code Online (Sandbox Code Playgroud)