여러 줄 선택 및 삭제를 위한 sed

여러 줄 선택 및 삭제를 위한 sed

주어진 입력 형식은 다음과 같습니다.

        set root='hd0,gpt3'
        if [ x$feature_platform_search_hint = xy ]; then
          search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt3 --hint-efi=hd0,gpt3 --hint-baremetal=ahci0,gpt3  dcf03c24-3d0d-4581-be1d-67b90f92a2c1
        else
          search --no-floppy --fs-uuid --set=root dcf03c24-3d0d-4581-be1d-67b90f92a2c1
        fi
        linux /boot/vmlinuz-5.4.0-33-generic root=UUID=dcf03c24-3d0d-4581-be1d-67b90f92a2c1 ro net.ifnames=0
        initrd /boot/initrd.img-5.4.0-33-generic

. . .

 if test x$grub_platform = xpc; then
   linux_suffix=16; 
 else
   linux_suffix= ; 
 fi

고쳐 쓰다:

처음에는 밝히지 않았어요. 질문grub2의 feature_platform_search_hint가 "No"일 수 있는 경우더 많은 정보가 있습니다. 즉, 다른 if 문이 있고 그 중 하나만 처리하고 싶습니다 feature_platform_search_hint. 이제 다른 if케이스를 위에 올려보세요.

전체 명령 블록을 무시/제거하면서 sed첫 번째 명령을 선택하고 싶습니다.searchfeature_platform_search_hintif

        set root='hd0,gpt3'
        search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt3 --hint-efi=hd0,gpt3 --hint-baremetal=ahci0,gpt3  dcf03c24-3d0d-4581-be1d-67b90f92a2c1
        linux /boot/vmlinuz-5.4.0-33-generic root=UUID=dcf03c24-3d0d-4581-be1d-67b90f92a2c1 ro net.ifnames=0
        initrd /boot/initrd.img-5.4.0-33-generic

나머지/나머지 줄은 그대로 유지됩니다.

이것이 sed내가 생각해낸 명령이다:

/feature_platform_search_hint/{
# remove if line and keep next
d; N; h;
# remove else block
N; N; N; d;
g; s/  search /search /;
}

하지만 예상대로 작동하지 않습니다.
이유와 해결 방법은 무엇입니까? 감사해요

답변1

sed '/^ *if \+/d;/^ *else *$/,/^ *fi *$/d' remove_if_block

/^ *if
위 줄에는 공백이 있으므로 "if" 앞에 공백과 별표가 있습니다.
귀하의 파일에 실제로 해당 파일이 있는지 모르겠습니다. 하지만 그런 경우에도 위의 코드는 작동할 것입니다. 누군가가 실수로 "else" 및 "fi" 뒤에 공백을 추가한 경우 보호를 위해 "else" 및 "fi" 뒤에 공백을 추가하십시오
else *$/. fi *$
다음으로 시작할 수도 있습니다.다른 곳에서, 그래서...

답변2

동일한 효과를 갖는 쉘 코드를 작성하려면 if명령문을 다음으로 바꾸십시오.if true; then

sed 's/^ *if \[.*]; then/if true; then # &/' file

이는 if명령문을 대체하지만 주석의 원래 코드를 유지합니다.

답변3

내 솔루션을 찾았습니다. 작동하지 않습니다 d. 다음 주기가 즉시 시작되고 나머지 명령은 처리되지 않습니다.

# input:
$ seq 9
1
2
3
4
5
6
7
8
9

# goal: remove line 4 (if), and 6~8 (3-line else block)

$ seq 9 | sed '/4/{N; s/^.*\n//; h; N; N; N; g; }'
1
2
3
5
9

관련 정보