简单的Shell脚本

时间:2011-05-24 05:35:49

标签: shell

我正在尝试编写一个简单的shell脚本。 脚本转到一个文件夹,循环遍历每个文件,并读取每个文件中的每一行并打印它们。

我做错了吗?

cd "My Directory Goes Here"

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

你错过了外部循环的do,你最好使用$()代替反引号(更容易阅读,更容易嵌套,任何现代都应该理解它{ {1}})。此外,您无需调用/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

如果你必须处理名字中包含空格的文件,那么你最好使用shell以外的东西,比如Perl,Ruby或Python。

相关问题