如何保留sed -n选项时,实现无匹配也输出单行内容?
-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
-nflag suppresses sed's default behavior of printing every line automatically. - The
s/[A-Z]//gcommand modifies the line (removing all uppercase letters if present) but doesn't trigger printing on its own. - The separate
pcommand 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

