LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   bash looping through a group of files alternatives to ls? (https://www.linuxquestions.org/questions/linux-software-2/bash-looping-through-a-group-of-files-alternatives-to-ls-933455/)

patolfo 03-08-2012 12:07 PM

bash looping through a group of files alternatives to ls?
 
Hello there guys, i am trying to work on reports, nasty things :p

i am doing this thing

Code:

for group in $(ls -1 grupos_*)
do
echo "Hello $group"
done

But i do know that using ls is not he right way any sugegstions

druuna 03-08-2012 12:31 PM

Hi,

Is this what you are after:
Code:

for group in grupos_*
do
  echo "Hello $group"
done

There's no need for the ls -1, grupos_* is expanded by the shell when processing the commands.

Hope this helps.

patolfo 03-09-2012 09:49 AM

thanks
 
yeah i found that yesterday forgot to put it on the forum, thanks a bunch for answering though

propofol 03-10-2012 01:06 AM

One other option which adds the flexibility of 'find' and avoids issues with spaces in file names:

Code:

find . -type f -name 'grupos_*' -print | while read group
do
  echo "Hello $group"
done

Regards,
Stefan

David the H. 03-10-2012 07:19 AM

Check out these links for details on how to handle this issue:

http://mywiki.wooledge.org/ParsingLs
http://mywiki.wooledge.org/DontReadLinesWithFor
http://mywiki.wooledge.org/BashFAQ/001

In a nutshell, you have to be very careful how you handle the output of commands, particularly ones that generate lists of filenames. Word-splitting can cause all sorts of problems if you don't do it right.

propofol's find solution is better, but still not completely safe as written. You should always use the -print0 option, and the corresponding syntax in the reading application. This is also detailed in the above links.


Finally, beware of this common pipe subshell pitfall:

http://mywiki.wooledge.org/BashFAQ/024


All times are GMT -5. The time now is 04:27 AM.