Text-Processing

試圖做一個完美的 sed 替換

  • May 11, 2022

我正在嘗試使用兩個命令進行 sed 替換。我不知道如何將這兩個命令組合在一起,以便一次正確地替換單詞。

我在這裡的角色是附加sc_admin到每個有單詞admin的地方。

以下是我能想到的所有單片語合:

access = read : [ admin ], write : [ admin, power ]
access = read : [ security_pan_power ], write : [ security_pan_power ]
access = read : [ * ], write : [ admin, wis_master, wis_read_only, wis_web ]
access = read : [ admin ]
access = read : [ admin, somerole ], write : [ admin, power ]

所以目前我正在使用 2 個 sed 命令進行替換

sed -e '/\bsc_admin\b/b' -e '/admin/ s/ *]/, sc_admin ]/' infile

正確替換讀取部分中的單詞 admin 但不替換寫入部分中的單詞 admin。

例如

access = read : [ admin, sc_admin ], write : [ admin, power ]
access = read : [ security_pan_power ], write : [ security_pan_power ]
access = read : [ *, sc_admin ], write : [ admin, wis_master, wis_read_only, wis_web ]
access = read : [ admin, sc_admin ]
access = read : [ admin, somerole, sc_admin ], write : [ admin, power ]
access = read : [ defadmin, somerole, sc_admin ], write : [ admin, power ]

儘管

sed -e '/\bsc_admin\b/b' -e '/admin/ s/ *] *$/, sc_admin ]/'

命令正確地在寫入部分附加單詞 admin,而它對讀取部分不做任何事情。

access = read : [ admin ], write : [ admin, power, sc_admin ]
access = read : [ security_pan_power ], write : [ security_pan_power ]
access = read : [ * ], write : [ admin, wis_master, wis_read_only, wis_web, sc_admin ]
access = read : [ admin, sc_admin ]
access = read : [ admin, somerole ], write : [ admin, power, sc_admin ]
access = read : [ defadmin, somerole ], write : [ admin, power ]

所以目前我正在執行一個命令,然後我正在執行第二個命令來修復文件。有沒有一種萬無一失的方法來組合命令以便獲得正確的輸出?

這是我想要的實際輸出:

access = read : [ admin, sc_admin ], write : [ admin, power, sc_admin ]
access = read : [ security_pan_power ], write : [ security_pan_power ]
access = read : [ * ], write : [ admin, wis_master, wis_read_only, wis_web, sc_admin ]
access = read : [ admin, sc_admin ]
access = read : [ admin, somerole, sc_admin ], write : [ admin, power, sc_admin ]

您可以執行以下操作sed

$ sed 's/\(\[ admin[^]]*\) /\1, sc_admin /g' file 
access = read : [ admin, sc_admin ], write : [ admin, power, sc_admin ]
access = read : [ security_pan_power ], write : [ security_pan_power ]
access = read : [ * ], write : [ admin, wis_master, wis_read_only, wis_web, sc_admin ]
access = read : [ admin, sc_admin ]
access = read : [ admin, somerole, sc_admin ], write : [ admin, power, sc_admin ]

  • \(\[ admin[^]]*\) 擷取字元串'

$$ admin<every character that is not a $$最後一個空格>。為此,我們將擷取包含在 之間\(...\),並用於[^]]*選擇不是 ( ^) ‘]’ 的字元。

  • \1, sc_admin 替換為擷取的組 ( \1) 並附加 ‘, sc_admin’。

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