steT
steT

Reputation: 109

how to loop with while using bash

my problem is that i have to count the numbers of files whit a common part of the name (Stefano) in a folder (Name) and for every name i want to echo the name with the number of count's. So names of the files in the folder will be like:

Stefano.A1
Stefano.B2
Stefano.H3 

The problem i have is how to echo the files.Because it's giving me the error:

ls Stefano* | wc -l: syntax error in expression (error token is "Stefano* | wc -l")  

here's the script

i=1

while [ $i -le $(ls Stefano* | wc -l) ]; do
      echo "Stefano*${i}"
      (i++)
done        

Upvotes: 0

Views: 217

Answers (4)

buydadip
buydadip

Reputation: 9407

I understand what you want now... you want to make $i -le $(ls Stefano* | wc -l) work for your while loop, so do the following:

i=1
while [ $i -le $(cd $1 && ls Stefano* | wc -l) ]
do
    echo "Stefano*${i}"
    ((i++))
done

I added cd so that you can execute the script from whatever directory you are in, without actually moving you from your current directory.

Upvotes: 0

Marc Bredt
Marc Bredt

Reputation: 955

find prints out the names for you :)

find -name "*Stefano*"

Upvotes: 1

Jeanno
Jeanno

Reputation: 2859

How about something more simple using a for loop. Something like

for file in Stephano*; do (i++); done

Upvotes: 0

anubhava
anubhava

Reputation: 784878

In BASH you can do:

i=1
for f in Stefano*; do
   echo "${f}${i}"
   ((i++))
done

Upvotes: 0

Related Questions