Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

linux - How to use while loop only to read filenames of a specific pattern

Suppose I have the following files in a particular directory.

ABC_TEXT_FILE_365.csv
ABC_TEXT_FILE_365_07h32.csv
BCD_TEXT_FILE_432.csv
BCD_TEXT_FILE_432_08h28.csv
FGB_TEXT_FILE_567.csv
FGB_TEXT_FILE_567_09h45.csv

Now I want to read only the files which has h*.csv pattern in them and then perform more operations.

But I know while read filename
will read all the filenames rite.? Is there any workaround for this. Please help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'm guessing you mean all files that match *h*.csv, in which case you might want to use a for loop like this:

for i in *h*.csv; do 
    while read line; do 
        # do some stuff, e.g. echo "$line"
    done < "$i"
done

In case it is a possibility that you have any directories that match the pattern, you might want to also add a test to ensure that each item in the loop is a file. That would be:

for i in *h*.csv; do 
    if [ -f "$i" ]; then 
        while read line; do 
            echo "$line" 
        done < "$i"
    fi
done

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...