Scroll through all files with a specific extension

for i in $(ls);do if [ $i = '*.java' ];then echo "I do something with the file $i" fi done 

I want to scroll through each file in the current folder and check if it matches a specific extension. The code above does not work, do you know why?

+44
file bash
Jan 24 '13 at 15:36
source share
5 answers

No fancy tricks:

 for i in *.java; do [ -f "$i" ] || break ... done 

Defender guarantees that if there are no corresponding files, the cycle will end without trying to process the nonexistent *.java file name. In bash (or shells supporting something like that), you can use the nullglob option nullglob simply ignore an inappropriate match and not enter the body of the loop.

 shopt -s nullglob for i in *.java; do ... done 
+94
Jan 24 '13 at 16:05
source share

correct answer: @chepner

 EXT=java for i in *.${EXT}; do ... done 

however, here's a little trick to check if the file name has the given extensions:

 EXT=java for i in *; do if [ "${i}" != "${i%.${EXT}}" ];then echo "I do something with the file $i" fi done 
+9
Jan 24 '13 at 16:45
source share

Add subfolders recursively,

 for i in `find . -name "*.java" -type f`; do echo $i done 
+4
09 Oct '14 at 9:14
source share

as @chepner says in his comment, you are comparing $ i with a fixed string.

To expand and fix the situation, you must use [[]] with the regex = ~ operator

eg:

 for i in $(ls);do if [[ $i =~ .*\.java$ ]];then echo "I want to do something with the file $i" fi done 

the regular expression to the right of = ~ is checked for the value of the left operator and should not be quoted (no error will be quoted, but will be compared with a fixed line and, most likely, a failure "

but @chepner's answer above using glob is a much more efficient mechanism.

+3
Jan 24 '13 at 16:42
source share

I agree with the other answers regarding the correct way to scroll through files. However, the OP asked:

The code above does not work, do you know why?

Yes!

Great article What is the difference between a test, [and [[?] Explains in detail that among other differences, you cannot use expression matching or pattern matching in the test command (which is short for [ )

 Feature new test [[old test [Example

 Pattern matching = (or ==) (not available) [[$ name = a *]] ||  echo "name does not start with an 'a': $ name"

 Regular Expression = ~ (not available) [[$ (date) = ~ ^ Fri \ ... \ 13]] && echo "It Friday the 13th!"
 matching

So this is why your script fails. If the OP is interested in an answer with the syntax [[ (which has the disadvantage that it is not supported on as many platforms as the [ command, I would be happy to edit my answer to include it.

EDIT: Any warnings on how to format the data in the response in a table would be helpful!

+1
Jan 24 '13 at 23:54
source share



All Articles