You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用sed删除包含password的行且不保留空行?

Solution to Remove Password Entries Without Empty Lines

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 the I flag)
  • [^\s]*: Matches all characters until the next whitespace (this captures the password value itself)
  • //: Replaces the entire matched pattern with nothing
  • gI: g for global replace (all occurrences in each line), I for 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:37:53