如何使用awk选择性处理文本行:保留指定#行并去#,移除无关#行
Correct Awk Command for Selective Line Processing
Let's get this sorted out for you! Your goal is to:
- Keep all lines that don't start with
#exactly as they are - For lines starting with
#, only keep those containingBuildorType, and remove the leading#from those lines
The Right Awk Command
Here's a concise, working command that does exactly what you need:
awk '/^#/ { if (/Build|Type/) { sub(/^#/, ""); print; next } } 1' input > output
Breakdown of How It Works
Let's break down each part so you understand what's happening:
/^#/: Targets lines that start with#- Inside this block: We check if the line contains either
BuildorTypewith/Build|Type/ - If it does,
sub(/^#/, "")removes the leading#, we print the modified line, thennextskips to the next line (so we don't process it again)
- Inside this block: We check if the line contains either
1: This is a shorthand in awk that evaluates to "true", which triggers the default action of printing the line. This handles all lines that don't start with#—they get printed as-is.
Why Your Previous Commands Didn't Work
Let's quickly address the issues with your attempts:
- First command:
awk '!/#/' input < out→ This matches any line that doesn't contain#anywhere, so it deletes all lines with a#entirely—way too broad for your needs. - Second command:
awk '/#/ && !/Build|Length/' input < out→ This matches lines that have a#and don't containBuildorLength, which is the opposite of what you want. That's why it left the unwanted#CN Filters:and# Flags = 1,2,3lines.
Test with Your Example Input
For your input:
#Build = NCBI Build 37 #CN Filters: # Flags = 1,2,3 # Type = Lowess Length Event ID 1 Gain xxx 10 Loss yyy
Running the correct command will produce your desired output:
Build = NCBI Build 37 Type = Lowess Length Event ID 1 Gain xxx 10 Loss yyy
内容的提问来源于stack exchange,提问作者justaguy
相关产品推荐
相关产品推荐

