Linux   发布时间:2022-05-08  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了awk – 提取与最后一列中的最小值对应的行大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要帮助从最后一列中具有最小编号的文件中提取所有行,即在这种情况下为7英寸.

示例文件如下:

文件1.txt的

VALID_PATH :  [102,80,112,109,23,125,111] 7
VALID_PATH :  [102,81,37,56,111]  7
VALID_PATH :  [102,111] 8
VALID_PATH :  [102,111]  8
VALID_PATH :  [102,110,111]    8
VALID_PATH :  [102,127,6,111] 9
VALID_PATH :  [102,88,111]    9
VALID_PATH :  [102,111] 10
VALID_PATH :  [102,111]  10
VALID_PATH :  [102,111]    10

在这里,我想提取所有具有7的行,这是最后一列中的最小值(最小值),并通过仅提取[]中包含的值将输出保存到另一个文件File-2.txt中,如图所示下面.

文件2.txt

102,111
102,111

我可以使用awk从最后一列获得最小值为“7”,使用如下代码:

awk 'BEGIN{getline;min=max=$NF}
NF{
    max=(max>$NF)?max:$NF
    min=(min>$NF)?$NF:min
}
END{print min,max}' File-1.txt

并使用awk代码仅打印方括号[]中的值,如下所示:

awk 'NR > 1 {print $1}' RS='[' FS=']' File-1.txt

但是,我被困在分配从第一个awk脚本获得的最小值,即在这种情况下为7,以提取[]中包含的相应数字,如File-2.txt中所示.

任何帮助解决这个问题将不胜感激.

解决方法

@Asha:@try:

awk '{Q=$NF;gsub(/.*\[|\]/,"");$NF="";A[Q]=A[Q]?A[Q] ORS $0:$0;MIN=MIN<Q?(MIN?MIN:Q):Q} END{print a[MIN]}' Input_file

稍后也会添加说明.

编辑:以下是同样的描述.

awk '{
Q=$NF;                    ##### Making last field of Input_file as NULl.
gsub(/.*\[|\]/,"");       ##### Using global substitution functionality of awk to remove everything till [ and then remove ] from the line as per your required output.
$NF="";                   ##### NULLIFying the last column of each line as you don't need them in your output.
A[Q]=A[Q]?A[Q] ORS $0:$0; ##### creaTing an array named A whose index is Q variable(whose value is already assigned prevIoUsly to last column),creaTing array A with index Q and concatenaTing it's value in itself.
MIN=MIN<Q?(MIN?MIN:Q):Q}  ##### CreaTing a variable named MIN(to get the minimum last value of each linE) and comparing it's value to each line's last field and keeping the minimum value in it as per requirement.
END{print a[MIN]}         ##### In end block of code prinTing the value of array A whose index is variable MIN to print all the lines whose index is variable named MIN.
' Input_file              ##### Mentioning the Input_file here.

大佬总结

以上是大佬教程为你收集整理的awk – 提取与最后一列中的最小值对应的行全部内容,希望文章能够帮你解决awk – 提取与最后一列中的最小值对应的行所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: