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

如何保留sed -n选项时,实现无匹配也输出单行内容?

Solution to Force Sed to Print Line Regardless of Substitution (With -n Flag)

Great question! Yes, you can absolutely achieve this without removing the -n option. Here's a straightforward approach:

Instead of relying on the p flag within the substitution command (which only prints if the substitution succeeds), split the substitution and print operations into separate sed commands:

# Test case 1: Line with uppercase letter
echo "700K" | sed -n 's/[A-Z]//g; p'
# Output: 700

# Test case 2: Line without uppercase letter
echo "700" | sed -n 's/[A-Z]//g; p'
# Output: 700

Why This Works:

  • The -n flag suppresses sed's default behavior of printing every line automatically.
  • The s/[A-Z]//g command modifies the line (removing all uppercase letters if present) but doesn't trigger printing on its own.
  • The separate p command then prints the current state of the line—whether it was modified by the substitution or remains unchanged.

Alternative (More Explicit) Approach:

If you want to explicitly handle both cases (substitution success vs failure), you can use sed's t command (which branches to the end of the script if a substitution occurred):

echo "700K" | sed -n 's/[A-Z]//gp; t; p'
echo "700" | sed -n 's/[A-Z]//gp; t; p'

Here, if the substitution succeeds, the p flag prints the modified line and the t command skips the final p. If no substitution happens, the final p prints the original line. However, the first approach is simpler and achieves the same result for your use case.

内容的提问来源于stack exchange,提问作者rbl651

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:38:02