通过bash脚本与多个目录中的文件进行交互 [英] Interacting with files from multiple directories via bash script

查看:141
本文介绍了通过bash脚本与多个目录中的文件进行交互的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我生成了一个脚本,该脚本可循环访问多个.csv文件,并将相关文件转换为UTF-8:

I generated a script that iterates through several .csv files, converting relevant files to 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?

推荐答案

您已经接受@Charles Duffy的回答,但是(如果我理解得很好),您的问题是关于将文件保存在不同目录中,如果您需要使用多个目录中的多个csv文件,则可以使用以下代码段:

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:

# 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

pathDir变量是一个包含不同目录路径的数组.

The pathDir variable is an array which contains the path of different directories.

第一个for循环遍历此数组以获取所有要检查的路径.

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.

这篇关于通过bash脚本与多个目录中的文件进行交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆