【问题标题】:Different behavior when running ls from within a script [duplicate]从脚本中运行 ls 时的不同行为[重复]
【发布时间】:2017-02-28 23:41:31
【问题描述】:

我想重命名几个以枚举方式命名的文件。我以前的方法是使用这个命令行:

FILES=`ls "someDir/"`; for f in $FILES; do echo "Processing file: $f"; done;

Echoing 文件名仅用于演示目的。以上产生了预期的输出:

Processing file: File1
Processing file: File2
Processing file: File3
...

但是,当我运行(我认为是同一件事)以下脚本时,它会将整个 ls 输出视为一个文件并生成以下输出:

SCRIPT:
#!/bin/bash
FILES=`ls "someDir/"`

for f in $FILES
do
    echo "Processing file: $f"
done

OUTPUT:
Processing file: File1
File2
File3
...

我无法理解它。此外,我什至不确定是否是ls 产生了这种行为。 是什么导致了这种行为?为什么?

【问题讨论】:

    标签: bash ls


    【解决方案1】:

    请参阅Why you shouldn't parse the output of ls(1),而不是使用process-substitution 来处理命令输出。

    #!/bin/bash
    
    while IFS= read -r -d '' file; do
        echo "$file"
        # Do whatever you want to do with your file here
    done < <(find someDir/ -maxdepth 1 -mindepth 1 -type f -print0 | sort -z)
    

    上述简单的find 列出了所需目录中的所有文件(包括带有空格/特殊字符的文件)。这里,find 命令的输出被馈送到stdin,由while-loop 解析。

    要对文件进行有序排序,请将sort -z 通过管道添加到find 命令输出。

    【讨论】:

    • 有没有办法告诉find 保持文件的实际顺序?因为我需要按照它们被命名的顺序处理它们。所以首先是File1,然后是File2,依此类推。但是find 会产生一个未排序的输出,例如File325File3File20、...。
    猜你喜欢
    • 1970-01-01
    • 2016-04-04
    • 2011-05-04
    • 2013-09-20
    • 2015-10-14
    • 2019-01-05
    • 2018-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多