【问题标题】:bash - redirect ls into custom scriptbash - 将 ls 重定向到自定义脚本
【发布时间】:2012-03-29 08:28:53
【问题描述】:

对于大学,我正在编写一个脚本来读取和显示 mp3 文件中的 id3 标签。参数将是文件,即

./id3.sh file1.mp3 file2.mp3 morefiles.mp3

我可以使用$0, $1 等读取参数并使用$# 获取参数的数量。如何让它读取 ls 命令的输出?

ls *.mp3 | ./id3.sh

【问题讨论】:

  • > 运算符用于将第一个命令的输出重定向到第二个文件(我想我目前没有登录到 unix 系统来检查它)你碰巧试试|

标签: linux bash shell io ls


【解决方案1】:

任何涉及扩展*.mp3 的解决方案如果.mp3 文件的数量太大以至于扩展的*.mp3 超出外壳的限制,则可能会失败。上面的解决方案都有这个问题:

ls *.mp3 | ...
for file in *.mp3; do ...

事实上,尽管ls *.mp3|xargs ... 是一个好的开始,但它也有同样的问题,因为它需要shell 扩展*.mp3 列表并将该列表用作ls 命令的命令行参数。

正确处理任意数量文件的一种方法是:

find . -maxdepth 1 -iname '*.mp3'|while read f; do
    do_something_one_file_at_a_time.sh "$f"
done

或者:

find . -maxdepth 1 -iname '*.mp3' -print0|xargs -0 do_something.sh

(两种变体都具有正确处理带有空格的文件名的好处,例如“Raindrops Keep Falling On My Head.mp3”。

请注意,在 do_something.sh 中,您需要执行 for file in "$@"; do ... 而不仅仅是 for file in $*;do ...for file in $@; do ...。 另请注意,如果文件名带有空格,则 amit_g 的解决方案会中断。)

【讨论】:

    【解决方案2】:

    ./id3.sh *.mp3 有什么问题?它是safer than any solution with ls,提供完全相同的通配符功能。这里不需要xargs,除非你使用old kernel并且enormous amounts of files

    【讨论】:

    【解决方案3】:
    ./id3.sh *.mp3 # if the number of files is not too many
    

    ls *.mp3 | xargs -n 10 ./id3.sh # if the number of files could be too many
    

    然后在id3.sh中

    while [ "$1" != "" ]
    do
        filename=$1
    
        #do whatever with $filename
    
        shift
    done
    

    【讨论】:

      【解决方案4】:

      我建议使用带有 -n 参数的管道和 xargs,在下面的示例中,id3.sh 脚本将被调用 最多 10 ls *.mp3 列出的文件。这非常重要,尤其是当您的列表中有数以千计的文件时。如果您省略 -n 10,那么您的脚本将在整个列表中仅调用一次。如果列表太长,您的系统可能会拒绝运行您的脚本。您可以试验每次调用脚本时要处理多少文件(例如,在您的情况下什么更有效)。

      ls *.mp3 | xargs -n 10 id3.sh
      

      然后您可以像这样读取 id3.sh 脚本中的文件

      while [ "$1" != "" ]; do
          #next file available in ${1}
          shift
      done
      

      【讨论】:

        【解决方案5】:

        ls *.mp3 > ./id3.sh 命令将用 mp3 列表覆盖您的 id3.sh 脚本。你可以试试这个:

        ./id3.sh `ls *.mp3`
        

        编辑:实际上,我在想什么?你有什么理由不能这样做吗?

        ./id3.sh *.mp3
        

        【讨论】:

          【解决方案6】:

          试试这个:

          ls *.mp3 | xargs id3.sh
          

          【讨论】:

          • 这是最好的解决方案。请注意,如果您想遍历脚本中的文件,还有比这更好的方法。例如,您可以直接在 for 循环中读取文件:for file in *.mp3; do printf "%s\n" "$file"; done
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-03-22
          • 1970-01-01
          • 1970-01-01
          • 2022-10-23
          • 1970-01-01
          相关资源
          最近更新 更多