sed 고급 명령어 및 패턴 매칭
이제 sed를 사용한 기본적인 치환 및 in-place 편집을 마스터했으므로, 몇 가지 더 고급 기능을 살펴보겠습니다.
- 다른 구분 기호 사용
- 특정 줄을 대상으로 주소 범위 사용
- 여러 명령 결합
다른 구분 기호 사용
치환 명령에서 슬래시 /를 구분 기호로 사용해 왔지만, sed는 모든 문자를 구분 기호로 사용할 수 있습니다. 이는 패턴 또는 대체 텍스트에 슬래시가 포함된 경우 특히 유용합니다.
파일 경로가 있는 파일을 만들어 보겠습니다.
echo "/usr/local/bin is in the PATH" > ~/project/paths.txt
echo "My config is in /etc/myapp/config.json" >> ~/project/paths.txt
/usr/local/bin을 /opt/bin으로 바꾸려면 슬래시를 사용하는 것이 혼란스러울 수 있습니다.
sed 's/\/usr\/local\/bin/\/opt\/bin/' ~/project/paths.txt
대신, #과 같은 다른 구분 기호를 사용할 수 있습니다.
sed 's#/usr/local/bin#/opt/bin#' ~/project/paths.txt
이것이 훨씬 더 읽기 쉽습니다! 출력은 다음과 같아야 합니다.
/opt/bin is in the PATH
My config is in /etc/myapp/config.json
다른 일반적인 구분 기호로는 |, :, 및 _가 있습니다.
주소 지정 - 특정 줄 대상 지정
sed를 사용하면 치환을 적용할 줄을 지정할 수 있습니다. 이는 명령 앞에 주소를 붙여서 수행됩니다.
번호가 매겨진 줄이 있는 새 파일을 만들어 보겠습니다.
echo "Line 1: This is the first line." > ~/project/numbered.txt
echo "Line 2: This is the second line." >> ~/project/numbered.txt
echo "Line 3: This is the third line." >> ~/project/numbered.txt
echo "Line 4: This is the fourth line." >> ~/project/numbered.txt
echo "Line 5: This is the fifth line." >> ~/project/numbered.txt
3 번째 줄에서만 "line"을 "row"로 바꾸려면:
sed '3 s/line/row/' ~/project/numbered.txt
출력은 다음과 같아야 합니다.
Line 1: This is the first line.
Line 2: This is the second line.
Line 3: This is the third row.
Line 4: This is the fourth line.
Line 5: This is the fifth line.
줄 범위를 지정할 수도 있습니다. 2 번째 줄부터 4 번째 줄까지 "line"을 "row"로 바꾸려면:
sed '2,4 s/line/row/' ~/project/numbered.txt
출력은 다음과 같아야 합니다.
Line 1: This is the first line.
Line 2: This is the second row.
Line 3: This is the third row.
Line 4: This is the fourth row.
Line 5: This is the fifth line.
또 다른 유용한 기능은 패턴을 기반으로 줄을 일치시키는 기능입니다. 예를 들어, "third" 또는 "fourth"를 포함하는 줄에서만 "line"을 "row"로 바꾸려면:
sed '/\(third\|fourth\)/ s/line/row/' ~/project/numbered.txt
출력은 다음과 같아야 합니다.
Line 1: This is the first line.
Line 2: This is the second line.
Line 3: This is the third row.
Line 4: This is the fourth row.
Line 5: This is the fifth line.
여러 명령 결합
-e 옵션을 사용하거나 세미콜론으로 명령을 구분하여 여러 sed 명령을 결합할 수 있습니다.
"first"를 "1st"로, "second"를 "2nd"로, "third"를 "3rd"로 단일 명령으로 바꿔보겠습니다.
sed -e 's/first/1st/' -e 's/second/2nd/' -e 's/third/3rd/' ~/project/numbered.txt
또는 세미콜론을 사용할 수 있습니다.
sed 's/first/1st/; s/second/2nd/; s/third/3rd/' ~/project/numbered.txt
두 명령 모두 동일한 출력을 생성해야 합니다.
Line 1: This is the 1st line.
Line 2: This is the 2nd line.
Line 3: This is the 3rd line.
Line 4: This is the fourth line.
Line 5: This is the fifth line.
이제 이러한 변경 사항을 영구적으로 적용해 보겠습니다.
sed -i 's/first/1st/; s/second/2nd/; s/third/3rd/' ~/project/numbered.txt
그리고 변경 사항을 확인합니다.
cat ~/project/numbered.txt
서수를 사용하여 업데이트된 텍스트를 볼 수 있습니다.