programing tip

쉘 스크립트에서 디렉토리의 파일 목록을 얻는 방법은 무엇입니까?

itbloger 2020. 7. 4. 11:08
반응형

쉘 스크립트에서 디렉토리의 파일 목록을 얻는 방법은 무엇입니까?


쉘 스크립트를 사용하여 디렉토리의 내용을 가져 오려고합니다.

내 스크립트는 다음과 같습니다

for entry in `ls $search_dir`; do
    echo $entry
done

$search_dir상대 경로는 어디 입니까? 그러나 $search_dir이름에 공백이있는 많은 파일이 있습니다. 이 경우이 스크립트는 예상대로 실행되지 않습니다.

나는 사용할 수 있다는 것을 알고 for entry in *있지만 현재 디렉토리에서만 작동합니다.

나는 그 디렉토리로 바꿀 수 있다는 것을 알고 사용했다가 for entry in *다시 변경하지만 내 특정 상황으로 인해 그렇게 할 수 없습니다.

나는이 개 상대 경로를 $search_dir하고 $work_dir, 나는 그들에게 등을 생성 / 그 안에 파일을 삭제, 읽기, 동시에 모두 일해야

이제 어떻게해야합니까?

추신 : 나는 bash를 사용합니다.


for entry in "$search_dir"/*
do
  echo "$entry"
done

여기에있는 다른 답변은 훌륭하고 귀하의 질문에 대답하지만, 이것은 "bash 디렉토리의 파일 목록 가져 오기"에 대한 최고의 Google 결과입니다 (파일 목록을 저장하려고했습니다). 그 문제에 대한 답 :

ls $search_path > filename.txt

특정 유형 (예 : .txt 파일) 만 원하는 경우 :

ls $search_path | grep *.txt > filename.txt

$ search_path는 선택 사항입니다. ls> filename.txt는 현재 디렉토리를 수행합니다.


이것은 구문이 이해하기 더 쉬운 곳에서 수행하는 방법입니다.

yourfilenames=`ls ./*.txt`
for eachfile in $yourfilenames
do
   echo $eachfile
done

./는 현재 작업 디렉토리이지만 경로를 바꿀 수 있습니다.
*.txtanything.txt를 반환합니다 . 터미널에 명령을 바로
입력하여 쉽게 나열 할 내용을 확인할 수 있습니다 ls.

기본적으로 yourfilenameslist 명령이 개별 요소로 반환하는 모든 것을 포함 하는 변수 를 만든 다음 반복합니다. 루프는 반복되는 변수 eachfile의 단일 요소 (이 경우 파일 이름)를 포함 하는 임시 변수 만듭니다 . 이것은 다른 답변보다 반드시 낫지는 않지만 ls명령과 for 루프 구문에 이미 익숙하기 때문에 직관적 입니다.


for entry in "$search_dir"/* "$work_dir"/*
do
  if [ -f "$entry" ];then
    echo "$entry"
  fi
done

find "${search_dir}" "${work_dir}" -mindepth 1 -maxdepth 1 -type f -print0 | xargs -0 -I {} echo "{}"

$ pwd; ls -l
/home/victoria/test
total 12
-rw-r--r-- 1 victoria victoria    0 Apr 23 11:31  a
-rw-r--r-- 1 victoria victoria    0 Apr 23 11:31  b
-rw-r--r-- 1 victoria victoria    0 Apr 23 11:31  c
-rw-r--r-- 1 victoria victoria    0 Apr 23 11:32 'c d'
-rw-r--r-- 1 victoria victoria    0 Apr 23 11:31  d
drwxr-xr-x 2 victoria victoria 4096 Apr 23 11:32  dir_a
drwxr-xr-x 2 victoria victoria 4096 Apr 23 11:32  dir_b
-rw-r--r-- 1 victoria victoria    0 Apr 23 11:32 'e; f'

$ find . -type f
./c
./b
./a
./d
./c d
./e; f

$ find . -type f | sed 's/^\.\///g' | sort
a
b
c
c d
d
e; f

$ find . -type f | sed 's/^\.\///g' | sort > tmp

$ cat tmp
a
b
c
c d
d
e; f

변형

$ pwd
/home/victoria

$ find $(pwd) -maxdepth 1 -type f -not -path '*/\.*' | sort
/home/victoria/new
/home/victoria/new1
/home/victoria/new2
/home/victoria/new3
/home/victoria/new3.md
/home/victoria/new.md
/home/victoria/package.json
/home/victoria/Untitled Document 1
/home/victoria/Untitled Document 2

$ find . -maxdepth 1 -type f -not -path '*/\.*' | sed 's/^\.\///g' | sort
new
new1
new2
new3
new3.md
new.md
package.json
Untitled Document 1
Untitled Document 2

노트:

  • . : 현재 폴더
  • -maxdepth 1재귀 적으로 검색하려면 제거
  • -type f: 디렉토리가 아닌 파일 찾기 ( d)
  • -not -path '*/\.*' : 돌아 오지마 .hidden_files
  • sed 's/^\.\///g': ./결과 목록에서 접두사 제거

다음은 디렉토리 내에 파일을 나열하는 다른 방법입니다 (다른 답변보다 효율적이지 않은 다른 도구 사용).

cd "search_dir"
for [ z in `echo *` ]; do
    echo "$z"
done

echo * Outputs all files of the current directory. The for loop iterates over each file name and prints to stdout.

Additionally, If looking for directories inside the directory then place this inside the for loop:

if [ test -d $z ]; then
    echo "$z is a directory"
fi

test -d checks if the file is a directory.


The accepted answer will not return files prefix with a . To do that use

for entry in "$search_dir"/* "$search_dir"/.[!.]* "$search_dir"/..?*
do
  echo "$entry"
done

On the Linux version I work with (x86_64 GNU/Linux) following works:

for entry in "$search_dir"/*
do
  echo "$entry"
done

참고URL : https://stackoverflow.com/questions/2437452/how-to-get-the-list-of-files-in-a-directory-in-a-shell-script

반응형