code

특정 확장자를 가진 모든 파일을 반복합니다.

codestyles 2020. 8. 23. 09:16
반응형

특정 확장자를 가진 모든 파일을 반복합니다.


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

현재 폴더의 각 파일을 반복하고 특정 확장자와 일치하는지 확인하고 싶습니다. 위의 코드가 작동하지 않습니다. 이유를 아십니까?


멋진 트릭이 필요하지 않습니다.

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

가드는 일치하는 파일이없는 경우 존재하지 않는 파일 이름을 처리하지 않고 루프가 종료되도록합니다 *.java. 에서 bash(비슷한 지원 또는 쉘), 당신은 사용할 수 있습니다 nullglob단순히 실패 일치를 무시하고 루프의 시체를 입력하지 옵션을 선택합니다.

shopt -s nullglob
for i in *.java; do
    ...
done

정답은 @chepner의

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

그러나 다음은 파일 이름에 지정된 확장자가 있는지 확인하는 작은 트릭입니다.

EXT=java
for i in *; do
    if [ "${i}" != "${i%.${EXT}}" ];then
        echo "I do something with the file $i"
    fi
done

재귀 적으로 하위 폴더 추가,

for i in `find . -name "*.java" -type f`; do
    echo "$i"
done

: 루프로 끝나는 모든 파일을 통해 .img, .bin, .txt접미사 및 파일 이름을 인쇄 :

for i in *.img *.bin *.txt;
do
  echo "$i"
done

또는 재귀 적 방식으로 (모든 하위 디렉터리에서도 검색) :

for i in `find . -type f -name "*.img" -o -name "*.bin" -o -name "*.txt"`;
do
  echo "$i"
done

@chepner가 그의 의견에서 말했듯이 $ i를 고정 문자열과 비교하고 있습니다.

상황을 확장하고 수정하려면 정규식 연산자 = ~와 함께 [[]]를 사용해야합니다.

예 :

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

= ~의 오른쪽에있는 정규식은 왼손 연산자의 값에 대해 테스트되며 따옴표로 묶어서는 안됩니다. (따옴표는 오류가 아니지만 고정 문자열과 비교하므로 실패 할 가능성이 높습니다. "

그러나 glob을 사용하는 위의 @chepner의 대답은 훨씬 더 효율적인 메커니즘입니다.


파일을 반복하는 올바른 방법에 대한 다른 답변에 동의합니다. 그러나 OP는 다음과 같이 물었습니다.

위의 코드가 작동하지 않습니다. 이유를 아십니까?

예!

An excellent article What is the difference between test, [ and [[ ?] explains in detail that among other differences, you cannot use expression matching or pattern matching within the test command (which is shorthand 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's Friday the 13th!"
matching

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

EDIT: Any protips for how to format the data in the answer as a table would be helpful!

참고URL : https://stackoverflow.com/questions/14505047/loop-through-all-the-files-with-a-specific-extension

반응형