命令输出优化:过滤无错误行及抑制特定输出行的通用方法
Let’s tackle your two questions with universal shell tricks that work across most Unix-like systems (Linux, macOS, BSD, etc.)—no need for scenario-specific hacks.
1. How to only keep output lines with no errors
First, it’s key to understand that shell commands use two separate output streams:
stdout(file descriptor 1): This is where normal, successful results get sentstderr(file descriptor 2): This is for error messages (like permission denied, missing files, etc.)
By default, both streams print to your terminal, which is why you’re seeing unwanted error lines. To isolate only error-free output, you just need to discard the stderr stream entirely:
Basic redirection: Send
stderrto the system’s "black hole" (/dev/null), which eats all input without a trace:find /var -name "chrom*" 2>/dev/nullThe
2>syntax tells the shell to redirect file descriptor 2 (stderr) to the path that follows.Works with pipelines too: If you want to process the error-free output further (like filtering with
grep), the same redirection applies seamlessly:find /var -name "chrom*" 2>/dev/null | grep "specific_text"
Note: Rarely, some poorly written tools might send error messages to stdout instead of stderr. In those cases, you’ll need to identify a pattern in the error lines and use the method below to exclude them.
2. How to suppress specific output lines (whether error or regular)
If you don’t want to discard all errors—just specific ones—or need to exclude certain lines from the normal output, here are flexible solutions:
Suppress specific error lines
First, merge stderr into stdout so you can filter both streams together with tools like grep or awk:
find /var -name "chrom*" 2>&1 | grep -v "Permission denied"
2>&1redirectsstderr(fd 2) to the same place asstdout(fd 1)grep -vreverses the match: it excludes any line containing the string you specify
To exclude multiple error patterns at once, use extended regex with grep -E:
find /var -name "chrom*" 2>&1 | grep -vE "Permission denied|No such file or directory"
Suppress specific lines from normal output
If the unwanted lines are part of the successful stdout stream, skip the 2>&1 redirection and just pipe to grep -v:
find /var -name "chrom*" 2>/dev/null | grep -v "unwanted_normal_line"
More flexible filtering with awk
For complex rules (e.g., excluding lines that match multiple patterns, or matching lines based on position), awk is a powerful, versatile tool:
find /var -name "chrom*" 2>&1 | awk '!/Permission denied/ && !/temp_file/'
The !/pattern/ syntax tells awk to exclude lines that match the pattern. You can combine multiple conditions with && (and) or || (or) for granular control.
Hope these methods give you the control you need over shell output—they’re core skills for working with command-line tools in any context.
内容的提问来源于stack exchange,提问作者C0deDaedalus

