如何使用awk删除文本文件指定列的最后一个字符?
Got it, let's tackle this with awk—it's the perfect tool for field-specific text tweaks like this.
The Command
Here's a clean, readable awk command that does exactly what you need:
awk '{ $4 = substr($4, 1, length($4)-1) $8 = substr($8, 1, length($8)-1) print }' your_input_file.txt
How It Works
Let me break down each part so you know what's going on:
substr($4, 1, length($4)-1): This grabs the 4th field ($4), pulls a substring starting at the first character (position 1) and ending at the second-to-last character (total length minus 1). We assign this modified string back to$4to update the field.- Same logic for
$8: We apply the exact same substring trick to the 8th field to strip its final character. print: Spits out the entire line with the modified 4th and 8th fields intact.
Example Test with Your Sample Input
If your input line is:
scff2 54 92 aa_bb_c4_1024_0_2 scff2 30 18 aa_bb_c4_1024_0_2 scff8 80 96 aa_bb_c4_24_0_2 scff8 14 42 aa_bb_c4_24_0_2 scff1 20 25 aa_bb_c4_98_0_1 scff4 11 25 aa_bb_c4_13_0_1 scff6 16 61 aa_bb_c4_84_0_1 scff6 15 16 aa_bb_c4_84_0_2
The command will output:
scff2 54 92 aa_bb_c4_1024_0 scff2 30 18 aa_bb_c4_1024_0 scff8 80 96 aa_bb_c4_24_0 scff8 14 42 aa_bb_c4_24_0 scff1 20 25 aa_bb_c4_98_0 scff4 11 25 aa_bb_c4_13_0 scff6 16 61 aa_bb_c4_84_0 scff6 15 16 aa_bb_c4_84_0
Bonus: Compact One-Liner
If you prefer a tight, no-line-breaks version, you can write it like this:
awk '{ $4=substr($4,1,length($4)-1); $8=substr($8,1,length($8)-1); print }' your_input_file.txt
内容的提问来源于stack exchange,提问作者Chudar

