2015-06-22 20 views
1

我正在研究一個小腳本,它只需要一個參數並讀取ls -l的輸出並顯示以該參數開頭的文件的用戶和名稱。缺少一個條件來顯示一個字符串

對於爲例:

$> ls -l | ./script.sh "ok" 
John ok_file 
Mark ok_test 

這裏是腳本的樣子:

#!/bin/bash                                             

while read hello 
do 
    name=$(echo $hello | cut -d' ' -f9 | grep $1) 

    if [ $? = 0 ] 
    then 
     log=$(echo $hello | cut -d' ' -f3) 
     echo -n $log' ' && echo $name 
    fi 
done 

它工作得很好,但我缺少一個條件:它不顯示開頭的文件該參數,但包含它的任何文件。

我該如何改變這個腳本來添加這個條件?

非常感謝。

回答

0

'grep'命令使用正則表達式來匹配文本。在表達式之前使用'^',以匹配行的開頭。所以,你可以行

name=$(echo $hello | cut -d' ' -f9 | grep $1) 

改變

name=$(echo $hello | cut -d' ' -f9 | grep "^"$1) 

,你應該得到預期的結果。

+0

非常感謝,這非常有用。 – Christopher

相關問題