remove trailing whitespace - shell script

1 minute read

windows 환경이라서 trailing whitespace 제거를 python으로 짰지만 *nix 환경이라면 shell script로 간단히 할 수 있다.

find . -type f -regex ".*\.\(h\|cpp\|hpp\)" | xargs sed --in-place 's/[[:space:]]\+$//'

find

find . -type f -regex ".*\.\(h\|cpp\|hpp\)"

조건에 맞는 파일을 찾는다.

find . -type f -name '*.h' -or -name '*.cpp' -or -name '*.hpp'

-regex 대신 -name -or 옵션을 연결해 사용해도 된다.

xargs

The name xargs, pronounced EX-args, means “combine arguments.” xargs builds and executes command lines by gathering together arguments it reads on the standard input. Most often, these arguments are lists of file names generated by find.

Overview - Finding Files

발음은 EX-args. stdin(standard input)을 인자(argument)로 쓸 수 있다. stdin을 날것으로 사용 안 하고 delimiter로 조각내서 쓴다. line oriented가 아니니 주의.

stdin에서 읽은 인자를 어디에 넣어서 실행하는가? 위치 정의가 없으면 마지막에 붙인다.

xargs sed --in-place 's/[[:space:]]\+$//'

즉, 이 명령은

sed --in-place 's/[[:space:]]\+$//' [stdin token]

이런 command를 만들어 실행한다.

xargs -i cp {} ~/backup/

참고로 인자 위치를 바꾸고 싶으면 -i 옵션을 사용하면 된다. {} 문자로 삽입 위치를 정의한다.

여기선 xargs를 썼다. find와 같이 사용할 땐, xargs 대신 find의 -exec 옵션을 사용해도 된다.

sed(stream editor)

sed --in-place 's/[[:space:]]\+$//' [filename]

--in-place 옵션을 붙여서 INPUTFILE에서 치환을 바로 실행. 치환 명령은 s/regexp/replacement/flags 이런 식. vim을 쓴다면 참 익숙한 형식이라 할 수 있겠다.

reference