gpt4 book ai didi

bash - 根据两个标准使用 awk 进行过滤

转载 作者:行者123 更新时间:2023-12-04 03:04:26 24 4
gpt4 key购买 nike

我之前有过类似的问题,但这次我需要一些更复杂的问题:

在一个看起来像这样的 txt 文件中:

147 186741 2S74M -162
83 647172 1S75M -221
163 584665 74M2S 271
99 658416 5S65M6S -272
163 718735 60M16S 243

我希望 awk 查看第 3 列,当它在第 2 或第 3 个位置遇到字符“S”时,它会查看第一列,当它遇到“147”或“83”时,它会丢弃那条线。其余的结果被传递给第二个 awk,它再次查看第 3 行,当它在末尾遇到字符“S”时,它然后查看第 1 列,如果它找到“99”或“163”它丢弃那些行。然后打印不符合这些过滤器的其余行。

我尝试了这些方法,但得到的是空白文件:

awk -Ft '{if ($3 ~ /S$/  && $1 ~ /99|163/)} {next}' | awk -Ft '{if ($3 ~ /^..?S/ && $1 ~ /147|83/)} {next} $6 ~ /S/ {print}' input.txt > output.txt 

最佳答案

由于您没有显示您正在使用的 Input_file,所以我根据您显示的 Input_file 举了我的示例,假设以下是您的 Input_file。

cat Input_file
147 186741 2S74M -162
83 647172 1S75M -221
163 584665 74M2S 271
99 658416 5S65M6S -272
163 718735 60M16S 243
147 186741 2K74M -162
83 647172 1K75M -221
163 584665 74M2K 271
99 658416 5S65M6K -272
163 718735 60M16S 243

下面是我的代码:

awk '(($1==147 || $1==83) && (substr($3,2,1)=="S" || substr($3,3,1)=="S")) || (substr($3,length($3))=="S" && ($1==99 || $1==163)){next} 1'  Input_file

现在,当我在 awk 之上运行时,我得到了如下这些值(我添加这些值只是为了检查我的代码是否正常工作)。

awk '(($1==147 || $1==83) && (substr($3,2,1)=="S" || substr($3,3,1)=="S")) || (substr($3,length($3))=="S" && ($1==99 || $1==163)){next} 1' Input_file
147 186741 2K74M -162
83 647172 1K75M -221
163 584665 74M2K 271
99 658416 5S65M6K -272

所以你可以看到所有那些在你提供的条件下没有出现的行都被打印了,给我一些时间也会在这里添加解释。

编辑:在这里也添加了对上述代码的解释,请不要运行它,因为我将它分成了不同的部分,仅供 OP 理解。

awk '(($1==147 || $1==83)\  ##First condition which re-presents your first awk starts here. checking conditions where $1 value is either 147 OR $1 value is 83
&& \ ## AND
(substr($3,2,1)=="S" \ ##substring of 3rd column is EQUAL to letter S
|| \ ## OR
substr($3,3,1)=="S"))\ ##substring of 3rd column is EQUAL to letter S
|| \ ##OR(means either that first aw condition should be TRUE or this following one), the second major condition for which you used second awk I clubbed both the awks into 2 major conditions here.
(substr($3,length($3))=="S"\##checking if substring of column 3s last letter is EQUAL to S here.
&& \ ## AND
($1==99 || $1==163)){ ##$1 value is either 99 or 163. So if either of above 2 major conditions are TRUE then perform following statements.
next ##next, it is awk keyword which will skip all further statements of line now, without doing any action.
}
1 ##awk works on method of condition and then action, so here I am making condition as TRUE by mentioning as 1 and NO action is mentioned so be default print action will happen which will print current line.
' Input_file ##mentioning Input_file here.

关于bash - 根据两个标准使用 awk 进行过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45873245/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com