2011-05-24 158 views
0

我想寫一個簡單的shell腳本。 腳本進入一個文件夾,遍歷每個文件,並讀取每個文件中的每一行並打印它們。簡單的外殼腳本

我做錯了什麼?

cd "My Directory Goes Here" 

for myFile in `ls` 
for line in `cat $myFile`; 
    do 
    echo "$line" 
    done 
done 
+0

幾件事情。 – 2011-05-24 05:42:32

回答

1

你缺少do的外環和你」使用$()代替反引號更好(更容易閱讀,更容易嵌套,任何現代/bin/sh都應該理解它)。此外,你不需要調用ls得到當前目錄的文件列表,你可以用*

# If you're trying to echo $myFile line by line and your lines 
# may have embedded whitespace, then you'll want to change the 
# input-field-separator to keep $(cat $myFile) for tokenizing 
# the file on whitespace. If your files don't have whitespace 
# in the lines, then you don't need to change IFS like this. 
IFS='' 

cd "My Directory Goes Here" 
for myFile in *; do 
    for line in $(cat $myFile); do 
     echo $line 
    done 
done 

以上會想念文件,如.dotfile但如果你需要那些可以使用find太:

for myFile in $(find . -type f -maxdepth 1); do 
    # As above 

如果你要處理包含名稱中有空格,那麼你最好使用比外殼如Perl和Ruby或Python以外的其他文件。

+0

這是選定的答案,但這是否工作? '1。'第一個答案不關心分隔符,它逐字地(用空格分隔)逐行掃描內容,而不是一行一行地''查找命令拋出錯誤,表示選項應該出現在參數之前。 '3.'使用貓的方式是貓虐待。 :) – Lobo 2011-05-26 00:20:07

+0

@Lobo:'1.'取決於文件的格式,雖然這裏有一些不明確的地方,但是設置IFS ='''會解決這個問題,所以我會添加一個更新。 ''''find'命令工作得很好,您使用的是什麼樣的過度嚴格的綁定和紀律'find'? '3.'那真的不是貓的虐待,貓的虐待是'貓的東西| mangler'而不是非虐待的'mangler 2011-05-26 05:34:15

1

使用find命令並將結果傳遞給cat。使用xargs來避免Argument list too long失敗。

find . -maxdepth 1 -type f -print0 | xargs -0 cat 

你可以只用cat $myFile,而不是採取每一行,並打印出來替換整個第二個for循環。

更新

oldIFS='$IFS' 
IFS=' 
' 
for line in `find . -maxdepth 1 -type f -print0 | xargs -0 cat`; do 
     echo $line 
done 
IFS='$oldIFS' 
如果你想做到這一點不改變

的IFS(內部字段分隔符) -

for file in `find . -maxdepth 1 -type f `; do 
    while read line; do 
     echo $line 
    done<$file 
done 
+0

謝謝,但我需要使用我讀的每一行的結果,是否可以將每行文本分配給一個變量並以某種方式使用它? – aryaxt 2011-05-24 05:43:02

+0

你已經得到了答案! – Lobo 2011-05-24 06:07:12

+0

@aryaxt答案已更新。 – Lobo 2011-05-26 00:09:48