/
ls 로 디렉토리만 출력하기
ls 로 디렉토리만 출력하기
개요
shell script 등을 작성할 때 특정 폴더내의 sub directory 를 순회하면서 특정 작업을 수행해야 하는 경우가 많이 있습니다.
ls 의 option 에는 directory 목록만 얻어오는 방법이 없으므로 ls 와 다른 command 를 사용해서 directory 목록을 얻어오는 방법을 정리해 봅니다
대상 폴더는 /target 이고 하위 directory 는 cs, draft, files, static 4개가 있다고 가정합니다.
방법
1.Using echo
$ echo target/* target/cs target/draft target/files target/static
2.Using ls -d */
ls 의 directory 만 추출하는 옵션인 -d 를 사용합니다.
$ ls -d target/* target/cs target/draft target/files target/static
ls 의 출력 결과를 pipe 로 다른 프로그램과 연결할 경우 파일명 컬러 출력을 위한 ANSI Code 가 붙어서 제대로 처리가 불가능합니다. 이럴 경우 다음과 같이 --color=never 옵션을 붙여주면 됩니다.
ls --color=never -d target/*
3.Using ls and grep
$ ls -l target | grep "^d"
drwxr-xr-x. 2 lesstif rnd 4096 2013-11-18 13:43 cs drwxr-xr-x. 2 lesstif rnd 4096 2013-11-18 13:43 draft drwxr-xr-x. 2 lesstif rnd 4096 2013-11-18 13:43 files drwxr-xr-x. 2 lesstif rnd 4096 2013-11-18 13:43 static
이제 awk 를 사용해서 9번째 필드를 출력하면 디렉터리이므로 이 결과를 다른 유틸리티에서 사용하면 됩니다.
$ ls -l |grep "^d"|awk '{print $9}'
4.Bash Script 사용
bash 에만 있는 기능을 이용하여 디렉터리만 추출할 수 있습니다.
경로명 맨 뒤에 / 로 끝나야 정상동작합니다.
$ for i in $(ls -d target/*/); do echo ${i%%/}; done target/cs target/draft target/files target/static
shell script 에서 사용할 경우 취향에 따라 아무거나 골라써도 무난합니다.
shell script 예제
#!/bin/sh DIRS=`ls -d target/*/` for i in ${DIRS};do echo "Entering directory=$i"; cd $i; cd ..; done
Ref
, multiple selections available,
Related content
Linux 파일 이름에서 경로와 확장자를 추출하는 법(Extract File Basename Without Path and Extension in Bash)
Linux 파일 이름에서 경로와 확장자를 추출하는 법(Extract File Basename Without Path and Extension in Bash)
More like this
directory 를 조회하는 ls 명령을 대체하는 exa 명령어 사용법
directory 를 조회하는 ls 명령을 대체하는 exa 명령어 사용법
More like this
파일 유형(file type)을 알려주는 linux file 명령어 사용법
파일 유형(file type)을 알려주는 linux file 명령어 사용법
More like this
설정 파일 변경 사항을 반영하는 linux source 명령어 사용법
설정 파일 변경 사항을 반영하는 linux source 명령어 사용법
More like this
여러 조건으로 파일을 찾는 Linux find 명령어 사용법
여러 조건으로 파일을 찾는 Linux find 명령어 사용법
More like this
Linux grep 사용법
Linux grep 사용법
More like this