본문 바로가기

리눅스

sed 명령어를 사용하여 파일에서 특정 라인을 삭제하는 방법

반응형

sed 명령어를 사용하여 파일에서 특정 라인을 삭제하는 방법(sed 라인 삭제)

sed는 텍스트 스트림을 처리하는데 사용되며 라인 삭제를 위해 d 명령어를 사용합니다.

sed -i 'Nd' 파일이름

여기서 N은 삭제하려는 라인의 번호입니다. 파일이름은 작업을 수행할 파일의 이름입니다. 이 명령은 해당 파일에서 지정된 라인 번호의 라인을 삭제하고 변경 사항을 해당 파일에 바로 적용합니다.

 

  • 특정 라인을 삭제
sed -i '5d' filename.txt
  • 5번째부터 10번째 줄까지를 삭제
sed -i '5,10d' filename.txt
  • pattern'을 포함하는 라인을 삭제
sed -i '/pattern/d' filename.txt
  • sedTestFile.txt 파일을 cat 명령을 사용하여 출력하고 출력된 내용에 대해서 grep 명령으로 특정 패턴을 검색하고 해당 패턴 주변 5줄을 출력
cat -n sedTestFile.txt | grep -C 5 'Moral of the story'
$ cat -n sedTestFile.txt | grep -C 5 'Moral of the story' 
    18
    19  The big bad wolf tried to climb down the chimney, but the third little pig had a big pot of boiling water on the fire. When the big bad wolf fell down the chimney, he fell into the boiling water and died.
    20
    21  The two little pigs were so happy that they invited the third little pig to live with them. They all lived happily ever after.
    22
    23  Moral of the story:
    24
    25  Hard work pays off. The third little pig worked hard to build his house out of bricks, and it paid off when the big bad wolf came.
    26
    27  Don't be lazy. The first two little pigs were lazy, and they paid the price when the big bad wolf came.
    28
  • sedTestFile.txt 파일에서 23번부터 27번까지의 줄을 출력
sed -n '23,27p' sedTestFile.txt
$ sed -n '23,27p' sedTestFile.txt
Moral of the story:

Hard work pays off. The third little pig worked hard to build his house out of bricks, and it paid off when the big bad wolf came.

Don't be lazy. The first two little pigs were lazy, and they paid the price when the big bad wolf came.
  • sedTestFile.txt 파일에서 23번부터 27번까지의 줄을 삭제하고 그 결과를 원본 파일에 적용
sed -i '23,27d' sedTestFile.txt
  • 백업 파일(sedTestFile.txt.bk)과 수정된 파일(sedTestFile.txt) 비교
diff -Nur sedTestFile.txt.bk sedTestFile.txt
$ diff -Nur sedTestFile.txt.bk sedTestFile.txt                 
--- sedTestFile.txt.bk  2023-11-14 16:21:55.866097959 +0900
+++ sedTestFile.txt     2023-11-14 16:24:01.267953654 +0900
@@ -20,10 +20,5 @@
 
 The two little pigs were so happy that they invited the third little pig to live with them. They all lived happily ever after.
 
-Moral of the story:
-
-Hard work pays off. The third little pig worked hard to build his house out of bricks, and it paid off when the big bad wolf came.
-
-Don't be lazy. The first two little pigs were lazy, and they paid the price when the big bad wolf came.
 
 Be prepared. The third little pig was prepared for the big bad wolf, and he was able to defeat him.

 

728x90
반응형