code

sed 초보자 : 폴더의 모든 항목 변경

codestyles 2020. 10. 14. 07:51
반응형

sed 초보자 : 폴더의 모든 항목 변경


폴더 (및 하위 폴더)의 모든 파일에서 정규식 찾기 및 바꾸기를 수행해야합니다. 이를 수행하는 Linux 쉘 명령은 무엇입니까?

예를 들어, 모든 파일에 대해이 작업을 실행하고 이전 파일을 새 텍스트로 덮어 쓰고 싶습니다.

sed 's/old text/new text/g' 

sed 만 사용하여 수행 할 수있는 방법은 없습니다. 최소한 find 유틸리티를 함께 사용해야합니다.

find . -type f -exec sed -i.bak "s/foo/bar/g" {} \;

이 명령은 .bak변경된 각 파일에 대한 파일을 생성 합니다.

메모:

  • 명령에 대한 -i인수 sed는 GNU 확장이므로 BSD로이 명령을 실행하는 경우 sed출력을 새 파일로 리디렉션 한 다음 이름을 바꿔야합니다.
  • find유틸리티는 -exec이전 UNIX 상자에서 인수를 구현하지 않으므로 | xargs대신 a를 사용해야합니다 .

기억하기 쉽기 때문에 find | xargs cmdover 사용하는 것을 선호합니다 find -exec.

이 예제는 현재 디렉토리 또는 그 아래의 .txt 파일에서 "foo"를 "bar"로 전역 적으로 대체합니다.

find . -type f -name "*.txt" -print0 | xargs -0 sed -i "s/foo/bar/g"

-print0-0당신의 파일 이름이 공백 펑키 문자를 포함하지 않는 경우 옵션은 생략 할 수 있습니다.


이식성을 위해 linux 또는 BSD에 특정한 sed 기능에 의존하지 않습니다. 대신 overwriteUnix 프로그래밍 환경에 대한 Kernighan 및 Pike의 책에서 스크립트를 사용합니다 .

명령은 다음과 같습니다.

find /the/folder -type f -exec overwrite '{}' sed 's/old/new/g' {} ';'

그리고 overwrite(내가 모든 곳에서 사용 하는) 스크립트는

#!/bin/sh
# overwrite:  copy standard input to output after EOF
# (final version)

# set -x

case $# in
0|1)        echo 'Usage: overwrite file cmd [args]' 1>&2; exit 2
esac

file=$1; shift
new=/tmp/$$.new; old=/tmp/$$.old
trap 'rm -f $new; exit 1' 1 2 15    # clean up files

if "$@" >$new               # collect input
then
    cp $file $old   # save original file
    trap 'trap "" 1 2 15; cp $old $file     # ignore signals
          rm -f $new $old; exit 1' 1 2 15   # during restore
    cp $new $file
else
    echo "overwrite: $1 failed, $file unchanged" 1>&2
    exit 1
fi
rm -f $new $old

아이디어는 명령이 성공한 경우에만 파일을 덮어 쓰는 것입니다. find사용하고 싶지 않은 곳에서도 유용 합니다.

sed 's/old/new/g' file > file  # THIS CODE DOES NOT WORK

쉘이 파일 sed을 읽기 전에 잘라 내기 때문 입니다.


Might I suggest (after backing up your files):

find /the/folder -type f -exec sed -ibak 's/old/new/g' {} ';'

Might want to try my mass search/replace Perl script. Has some advantages over chained-utility solutions (like not having to deal with multiple levels of shell metacharacter interpretation).


In case the name of files in folder has some regular names (like file1, file2...) I have used for cycle.

for i in {1..10000..100}; do sed 'old\new\g' 'file'$i.xml > 'cfile'$i.xml; done

참고URL : https://stackoverflow.com/questions/905144/sed-beginner-changing-all-occurrences-in-a-folder

반응형