使用Awk根据第5字段模式修改第4字段内容并删除第5字段的执行异常问题
Fixing Your Awk Script to Meet the Expected Output
Let's break down what's wrong with your current script and fix it step by step.
The Issues with Your Current Command
Your existing script has a few critical problems that lead to the messed-up output:
- Syntax & Field Handling Error: In the first awk command,
print $ ":" "1/1"is invalid—$needs a field number (you meant$4), but even then, you're only printing the modified $4 instead of preserving the first three fields. This is why your output has extra, misplaced values. - Incomplete Field Preservation: You aren't retaining the first three columns (
$1,$2,$3) when modifying$4, so the output loses crucial data. - Inefficient Pipeline: Using two awk commands is unnecessary here—we can handle all logic in a single script, which is cleaner and less error-prone.
- Buggy $5 Removal: The second awk's
!($5="")is a confusing and unreliable way to remove the 5th field.
The Corrected Awk Script
We can handle the prefix addition and field removal in one awk invocation. Here's the working command:
awk -F'\t' 'BEGIN{OFS="\t"} { # Determine the correct prefix based on $5 prefix = ($5 ~ /High Copy Gain|Homozygous Copy Loss/) ? "1/1:" : "0/1:" # Update $4 with the prefix $4 = prefix $4 # Remove the 5th field by clearing it $5 = "" # Print the modified line print $0 }' f.txt
How This Works:
- Field Separator Setup: We set both input (
-F'\t') and output (BEGIN{OFS="\t"}) separators to tabs to maintain the file's original structure. - Prefix Logic: Using a ternary operator, we check if
$5matches eitherHigh Copy GainorHomozygous Copy Loss—if yes, we use1/1:as the prefix; otherwise (for all CN-related entries), we use0/1:. - Modify $4: We prepend the prefix to the original
$4value, separated by a colon as required. - Remove $5: Clearing
$5tells awk to exclude it when printing$0(the entire line, now without the 5th field).
Verifying the Output
Running this script on your input file will produce exactly the expected result:
chr1 629031 GT:CN 1/1:4 chr1 632301 GT:CN 0/1:3 chr1 6440431 GT:CN 0/1:2 chr1 16691021 GT:CN 1/1:1 chr1 6440431 GT:CN 0/1:0
内容的提问来源于stack exchange,提问作者justaguy
相关产品推荐
相关产品推荐

