如何使用sed删除包含password的行且不保留空行?
Your original sed command was deleting everything from "password" to the end of the line, which is why you ended up with empty lines or truncated content. Instead, we need to target only the specific "Password:XXX" tokens and remove them without affecting the rest of the line.
Correct Sed Command
Use this command to remove all case-insensitive "Password:..." entries (along with the preceding space) from your file:
sed -i "s/\sPassword:[^\s]*//gI" your_file.txt
Breakdown of the Command:
\s: Matches the whitespace before the "Password:" entry (ensures we don't leave a trailing space after the previous field)Password:: The literal string we're targeting (case-insensitive due to theIflag)[^\s]*: Matches all characters until the next whitespace (this captures the password value itself)//: Replaces the entire matched pattern with nothinggI:gfor global replace (all occurrences in each line),Ifor case-insensitive matching
Removing Empty Lines (If Needed)
If some lines become empty after removing password entries and you want to delete those entirely, add a second command to the sed call:
sed -i -e "s/\sPassword:[^\s]*//gI" -e "/^\s*$/d" your_file.txt
The -e "/^\s*$/d" part deletes any lines that are empty or contain only whitespace.
Example Output
Applying the first command to your input:
Original:
Database Name:Mydb DatabaseServer:DbServer Password:Example Username:User1 Database Name:Mydb1 DatabaseServer:DbServer1 Password:Example1 Username:User11
Result:
Database Name:Mydb DatabaseServer:DbServer Username:User1 Database Name:Mydb1 DatabaseServer:DbServer1 Username:User11
This gives you exactly the output you're looking for, with no empty lines or truncated content.
内容的提问来源于stack exchange,提问作者Naren

