2011-06-11 23 views
3

我想創建一個我可以在命令行上運行一個Ruby腳本,將:Ruby腳本,將調用如ls命令行命令-l,然後採取特定列喂到另一個FN

1. run a command line command like e.g. "ls -l" 
2. then I pass an argument for a specific column from the output of #1 
3. for each column specified in #2, it will run another command 

ls -l只是一個例子,我想這是通用的。

我對ruby很陌生,仍然沒有得到這樣的一些,所以如果你可以讚揚你做了什麼以及如何做,那對我會有很大的幫助。

+0

您的問題描述有點不清楚。你可以發佈一個示例調用和腳本的預期輸出嗎? – sepp2k 2011-06-11 01:50:24

回答

3

我在管道中經常使用|awk '{print $5;}'(將5替換爲您選擇的單索引列)。如果您使用了一些有趣的命令行開關,則可以獲得類似ruby的簡單單線程。比較:

$ ls -l | awk '{print $5;}' 

404 
16 
10 
8733 

VS

$ ls -l | ruby -ne "a = split; puts a[4];" 
nil 
404 
16 
10 
8733 

ruby -n地方在你的代碼中的隱含while gets() do .. end循環,ruby -e通過在命令行腳本元素。將兩者結合起來,你就可以獲得一些簡單的單線腳本功能,類似於perl -neawk(1)

的聯機幫助提到了另一種選擇,看起來非常有用:

-a    Turns on auto-split mode when used with -n or 
       -p. In auto-split mode, Ruby executes 
         $F = $_.split 
       at beginning of each loop. 

胡安指出,如何使用它(單引號阻止我的殼,bash(1),從解釋$F[3]作爲變量引用):

$ ls -l | ruby -ane 'puts $F[3]' 
nil 
root 
root 
root 
root 
sarnold 
sarnold 
... 
+0

最後一條命令的正確格式是'ls -l |紅寶石'放$ F [3]''。順便說一句,你的回覆對我來說非常有用。謝謝:) – 2011-09-18 23:55:29

+0

@Juan,非常感謝您的糾正。 – sarnold 2011-09-19 22:46:38

相關問題