2009-06-11 46 views
23

我在.aliases以下別名:如何在xargs中使用別名命令?

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的。

+0

下面是一個類似的(雖然不完全相同)的問題:http://stackoverflow.com/questions/513611/xargs-doesnt-recognize-bash-aliases – 2010-03-08 12:07:48

回答

22

別名是shell特有的 - 在這種情況下,最有可能是bash特有的。要執行別名,您需要執行bash,但僅針對交互式shell加載別名(更精確地說,.bashrc只能在交互式shell中讀取)。

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

把它們放在一起: 慶典-IC CMD運行CMD在一個交互的shell,其中CMD可以在你的.bashrc定義的bash函數/別名。

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

應該做你想做的。

編輯:我看你已經將問題標記爲「tcsh」,所以特定於bash的解決方案不適用。有了tcsh,你不需要-i,因爲它似乎讀取.tcshrc,除非你給-f

試試這個:

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

它的工作對我的基本測試。

7

轉向 「GI」 爲腳本,而不是

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

#!/bin/sh 
exec /bin/grep -i "[email protected]" 

不要忘記標記文件的可執行文件。

5

的建議here是爲了避免和xargs的使用「而改爲」循環代替的xargs:

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

見接受的答案在上面的改進處理文件名中使用空格或換行符的鏈接。

+0

如果文件名中有空格或換行符,這不是很好作爲帶-0選項的xargs(並使用-print0查找)。 – 2009-06-11 06:10:18

+0

謝謝,我編輯指出。 – 2009-06-11 14:05:59

0

對於tcsh(不具備的功能),你可以使用:

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

對於bash/KSH/sh的,你可以創建在外殼的功能。

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

    foobar foo bar 

請記住,在shell中使用反引號比從多個角度使用xargs更有優勢。將函數放在你的.bashrc中。

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 
0

這是特殊字符安全:

find . -print0 | xargs -0 bash -ic 'echo gi foo "[email protected]"' -- 

-print0-0使用\0NUL - 終止的字符串,因此當文件名中有空格時不會發生奇怪的事情。

bash設置命令字符串作爲$0後的第一個參數,所以我們傳遞一個僞參數(--),以便通過find列出的第一個文件沒有得到通過$0消耗。