简体   繁体   English

通过bash脚本与来自多个目录的文件进行交互

[英]Interacting with files from multiple directories via bash script

I generated a script that iterates through several .csv files, converting relevant files to UTF-8: 我生成了一个脚本,该脚本可循环访问多个.csv文件,并将相关文件转换为UTF-8:

#!/bin/bash

cd /home/user/prod/
charset="text/plain; charset=iso-8859-1"

for file in *.csv; do
    if [[ $(file -i "$file") == "$file: $charset" ]]; then
        iconv -f ISO-8859-1 -t UTF-8 "$file" > "$file.new";
        mv -f "$file.new" "$file";
fi
done

That works, but what I'd really like is to iterate through files that reside in different paths. 那行得通,但是我真正想要的是遍历驻留在不同路径中的文件。 I tried to start by setting one path (rather than defining a current directory), but I couldn't get it to work: 我试图从设置一个路径开始(而不是定义当前目录),但无法使其正常工作:

#!/bin/bash

path="/home/user/prod"
charset="text/plain; charset=iso-8859-1"

for file in "$path/*.csv"; do
    if [[ $(file -i "$file") == "$file: $charset" ]]; then
        iconv -f ISO-8859-1 -t UTF-8 "$file" > "$file.new";
        mv -f "$file.new" "$file";
fi
done

What's the best way to do this by setting the path? 设置路径的最佳方法是什么? What about handling files (same extension) that reside in different paths? 如何处理驻留在不同路径中的文件(相同扩展名)?

You stop the glob from being expanded when you quote it in 当您引用它时,可以阻止全局扩展

for file in "$path/*.csv"; do

Instead, quote the expansion but not the glob: 相反,请引用扩展而不是glob:

for file in "$path"/*.csv; do

You already accepted the answer of @Charles Duffy but (if I understood well) your question is about having files in different directories so if you need to work with multiple csv files on multiple directories you can use the following snippet: 您已经接受@Charles Duffy的答案,但是(如果我很好理解),您的问题是关于文件位于不同目录中的,因此,如果您需要在多个目录中使用多个csv文件,则可以使用以下代码段:

# array containing the different directories to work with
pathDir=("/foo/bar/dir1" "/buzz/fizz/dir2")

for dir in "${pathDir[@]}" # For each directory
do
    for file in "$dir/"*.csv; do # For each csv file of the directory

        if [[ $(file -i "$file") == "$file: $charset" ]]; then
            iconv -f ISO-8859-1 -t UTF-8 "$file" > "$file.new";
            mv -f "$file.new" "$file";
        fi

    done
done

The pathDir variable is an array which contains the path of different directories. pathDir变量是一个包含不同目录路径的数组。

The first for loop iterate through this array to get all the paths to check. 第一个for循环遍历此数组以获取所有要检查的路径。

The second for loop as in the previous answer iterate through the files of the current tested directory. 如上一个答案中的第二个for循环,迭代当前测试目录的文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM