【问题标题】:How can I run a bash script on all files with a json extension in a directory?如何对目录中所有带有 json 扩展名的文件运行 bash 脚本?
【发布时间】:2019-12-06 07:13:12
【问题描述】:

我需要使用我拥有的脚本将一堆 json 文件转换为 CSV。这些文件位于克隆的 Github 存储库中,因此目录中有多个文件夹,其中包含 json 文件。该脚本需要遍历所有文件夹并转换 json 文件。我该怎么做?

我试过了

for FILE in `ls /Users/user.name/Desktop/cloned_git_repo/*json`; do ./json_convert.sh
$FILE; done

但是,它返回

ls: /Users/user.name/Desktop/cloned_git_repo/*json: No such file or directory.

任何帮助将不胜感激,因为这将使我的生活轻松 100 万倍。注意:我在 Mac 上。

【问题讨论】:

标签: bash directory


【解决方案1】:

尽量避免迭代ls 的输出,因为它的输出可能因系统而异。尝试使用find

find . -type f -name "*.json" | xargs ./json_convert.sh

或者,如果您的脚本一次只接受一个参数:

find . -type f -name "*.json" -print0 | while read -d $'\0' file
do
    ./json_convert.sh "$file"
done

【讨论】:

  • xargs 具有 -n1 选项,一次采用一个参数。默认情况下xargs 解释引号和空格等,你想要xargs -d $'\n'。或-print0 | xargs -0
猜你喜欢
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-29
  • 2021-02-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多