Ubuntu下如何用sed/awk/正则定位CSS选择器并修改内部配置?
Got it, let's walk through this step by step since you're new to sed/awk and regex. First off, always back up system files before editing them—this is a critical safety net if something goes wrong.
Step 1: Backup the Original File
Run this command to create a backup copy of the gdm3.css file:
sudo cp /etc/alternatives/gdm3.css /etc/alternatives/gdm3.css.bak
If you ever need to revert to the original, just run sudo cp /etc/alternatives/gdm3.css.bak /etc/alternatives/gdm3.css.
Method 1: Using sed (Quick and Direct)
sed is perfect for line-based, targeted replacements. Here's the command to modify the selector's style block:
sudo sed -i '/\.login-dialog-banner/{n;s/{ color: #d6d6d1; }/{ color: rgba(255,255,255,1); font-size: 14; text-align: center; }/}' /etc/alternatives/gdm3.css
Let's break down what this does:
/\.login-dialog-banner/: Matches the line with your target selector (we escape.because it's a special character in regex that matches any character){n;s/.../.../}:njumps to the next line (where the actual style block is located)s/old/new/replaces the original style block with your custom configuration
-i: Edits the file directly (no need to redirect output to a separate file)
Method 2: Using awk (More Readable for Context-Aware Changes)
awk excels at handling context-dependent edits. Since awk doesn't support in-place editing directly, we'll use a temporary file to handle the change:
sudo awk 'BEGIN{flag=0} /\.login-dialog-banner/{flag=1; print; next} flag==1 && /\{ color: #d6d6d1; \}/{print "{ color: rgba(255,255,255,1); font-size: 14; text-align: center; }"; flag=0; next} {print}' /etc/alternatives/gdm3.css > temp.css && sudo mv temp.css /etc/alternatives/gdm3.css
Here's the logic behind this command:
BEGIN{flag=0}: Initialize a flag to track if we've found the target selector/\.login-dialog-banner/{flag=1; print; next}: When we hit the selector line, set the flag to 1, print the line, and skip to the next lineflag==1 && /\{ color: #d6d6d1; \}/{...}: When the flag is active and we match the original style block, print your new style, reset the flag, and skip{print}: Print all other lines exactly as they are
Verify the Change
To confirm your modification worked, run this command to check the selector and its updated style:
grep -A1 "\.login-dialog-banner" /etc/alternatives/gdm3.css
You should see your new style block listed right under the .login-dialog-banner line.
内容的提问来源于stack exchange,提问作者ruh8n2

