Chubaka
Chubaka

Reputation: 3135

redirect file names into a variable

Assume there are several files like the following

CLIENT_1.csv
CLIENT_2.csv
CLIENT_3.csv
CLIENT_4.csv

Is there any shell command/awk that we can use to direct the 1,2,3,4 into a variable named "ID"? So that we can do the following

if [ ${ID} != 4 ]
then
blah blah blah
fi

Upvotes: 0

Views: 39

Answers (2)

Nelda.techspiress
Nelda.techspiress

Reputation: 643

This is pretty much a repeat of this question. How to iterate over files in a directory with Bash?

It uses filename wildcarding to iterate through the list. In your case you would use:

for filename in /mydirectory/CLIENT_*.csv; do
   #whatever you wanted to do
done

Here is another way to do it where the filename string pattern is a variable. bash: filenames with wildcards in variables The file names are stored in the variable file (looking at the accepted answer) after the wildcarding is expanded in the for loop initialization. Again using the power of wildcarding your example would look something like this:

putfile=CLIENT_*.csv
for file in $putfile; do #whatever you wanted to do
done

Upvotes: 0

ilkkachu
ilkkachu

Reputation: 6517

To get the number part for each file:

for file in CLIENT_*.csv ; do
    id=${file%.csv}         # remove trailing '.csv'
    id=${id#CLIENT_}        # remove leading 'CLIENT_'
    if [ "$id" != 4 ] ; then ... ; fi
done

Upvotes: 2

Related Questions