Interacting with files from multiple directories v

2020-04-16 19:07发布

问题:

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?

回答1:

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

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

The first for loop iterate through this array to get all the paths to check.

The second for loop as in the previous answer iterate through the files of the current tested directory.



回答2:

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:

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


标签: linux bash shell