Awk

我如何用 sed 或 awk 註釋掉兩行的塊(一個唯一行後跟一個縮進的非唯一行)?

  • January 16, 2022

我寫了以下程式碼:

#!/usr/bin/bash

wireless_state=$(ip l |grep "3: wlp" |sed -E 's/^.*state ([DOWNUP]{2,4}).*/\1/')
ethernet_state=$(ip l |grep "2: en" |sed -E 's/^.*state ([DOWNUP]{2,4}).*/\1/')

if [[ $ethernet_state == "DOWN" ]]; then
 sed -i 's/^Match Address 192.168.18.109/#Match Address 192.168.18.109/;s/^Match Address 192.168.18.112/#Match Address 192.168.18.112/' sshdc
fi

sshdc的副本在哪裡/etc/ssh/sshd_config。我的尾巴是/etc/ssh/sshd_config這樣的:


#Match Address 192.168.18.103 
   #PubkeyAuthentication yes
Match Address 192.168.18.109 
   PubkeyAuthentication yes
#Match Address 192.168.18.111
   #PubkeyAuthentication yes
Match Address 192.168.18.112
   PubkeyAuthentication yes

我希望我的程式碼註釋掉兩行的整個塊,例如

#Match Address 192.168.18.109
#    PubkeyAuthentication yes

而到目前為止,我的程式碼只註釋掉了該塊的第一行,如下所示:

#Match Address 192.168.18.109
   PubkeyAuthentication yes

一行 asMatch Address 192.168.18.109是唯一的,而 PubkeyAuthentication yes不是,並且PubkeyAuthentication no文件頭部的某處也有未縮進。我如何使用 、 或任何其他 GNU/Linux 實用程序完成此類sed任務awk?請讓 Python 中的解決方案超出此問題的範圍。

至少對於 GNU sed(GNU/Linux 的預設設置),您可以使用以下形式的地址範圍

addr1,+N

    Matches addr1 and the N lines following addr1.

所以例如

$ sed '/^Match Address 192\.168\.18\.109/,+1s/^/#/' sshdc
#Match Address 192.168.18.103
   #PubkeyAuthentication yes
#Match Address 192.168.18.109
#    PubkeyAuthentication yes
#Match Address 192.168.18.111
   #PubkeyAuthentication yes
Match Address 192.168.18.112
   PubkeyAuthentication yes

隨著awk使用getline

awk '/^Match/ {$0="#"$0 ; print ; getline ; $0="#"$0 } 1' file

或者通過設置一個自(去)啟動標誌:

awk '/^Match/ || b {$0="#$0" ; b=!b } 1' file

引用自:https://unix.stackexchange.com/questions/686526