对脚本输出进行排序,但将行保持在一起

对脚本输出进行排序,但将行保持在一起

我想读出一些文件并对输出进行排序。

例如:

cat example.conf  
Order: 0   
Package: example 

cat another.conf  
Order: 2  
Package: another

cat file.conf  
Order: 1  
Package: file

我用以下方式输出它们awk '/Order|Package/' conf/*.conf

Order: 2  
Package: another  
Order: 0  
Package: example  
Order: 1  
Package: file

我希望输出按后面的数字排序Order:,但不会破坏行之间的关系,例如:

Order: 0  
Package: example  
Order: 1  
Package: file  
Order: 2  
Package: another

答案1

如果您的 GNU awk> 4.0,并假设该Order记录始终位于该Package记录之前,则

gawk '/^Order/ {order = $2} /^Package/ {p[order] = $0} 
  END {
    PROCINFO["sorted_in"] = "@ind_num_asc"
    for (i in p) {print "Order:", i; print p[i]}
  }
' conf/*.conf
Order: 0
Package: example
Order: 1
Package: file
Order: 2
Package: another

对于老年人,gawk您可以使用asorti

gawk '/^Order/ {order = $2} /^Package/ {p[order] = $0} 
  END {
    n = asorti(p,b)
    for (i=1;i<=n;i++) {print "Order:", i; print p[b[i]]}
  }
' conf/*.conf

答案2

适用于仅包含两行的文件。

sed -n 'N; s/\n//p' *.conf | sort | sed -n 's/\(Package\)/\n\1/p'

解释:

  1. sed -n 'N; s/\n//p' *.conf- 删除两行之间的换行符,即将两行连续的行连接到一行中。
  2. sort- 对上一步中创建的长行进行排序。
  3. sed -n 's/\(Package\)/\n\1/p'- 将换行符返回到其位置。

输出:

Order: 0   
Package: example 
Order: 1  
Package: file
Order: 2  
Package: another

答案3

一个简单的 Unix 方法:

awk '/Order|Package/' conf/*.conf |           # get your usual output
    paste - - |                               # convert two lines to one
        sort -n -k2,2 |                       # sort numerically
            awk '{print $1,$2;print $3,$4}'   # re-print in two columns

答案4

这也有效:

grep -e ^Order -e ^Package `grep ^Order *.conf | awk -F: '{printf("%s:%s\n",$NF,$0);}' |sort| awk -F: '{print $2}'`

说明(下面的多行格式仅用于演示,它确实不是在 bash 中工作,因为生成的单行命令无法处理评论):

$ grep -e ^Order -e ^Package ` \                # grep for lines starting with "Order" or "Package"; start nested command 
> grep ^Order *.conf | \                        # grep for lines starting with "Order" in files *.conf
> awk -F: '{printf("%s:%s\n",$NF,$0);}' | \     # prefixing order number with a separating colon
> sort | \                                      # sort by order number
> awk -F: '{print $2}' \                        # extract file name alone ; now filenames are ordered by the order number contained within them
> `                                             # end nested command

相关内容