使用命令行工具对行子组进行排序 [英] Sort subgroups of lines with command-line tools

查看:174
本文介绍了使用命令行工具对行子组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图找到一种方法,使用标准的命令行工具,bash,awk,排序,除非找不到使用perl或类似的方式排序。

I've been trying to find a way of sorting this with standard commandline tools, bash, awk, sort, whatever but can't find a way apart from using perl or similar.

任何提示?

输入数据

header1
3
2
5
1

header2
5
1
3
.....
.....

输出数据

Output data

header1
1
2
3
5

header2
1
....


$ b b

感谢

Thanks

推荐答案

假设节由空行分隔,标题不一定包含字符串header 。以原始顺序保留部分,以便排序是稳定的。从stdin读取,显示在stdout上。

Assumes sections are separated by blank lines and the header doesn't necessarily contain the string "header". Leaves the sections in the original order so the sort is stable. Reads from stdin, displays on stdout.

#!/bin/bash

function read_section() {
    while read LINE && [ "$LINE" ]; do echo "$LINE"; done
}

function sort_section() {
    read HEADER && (echo "$HEADER"; sort; echo)
}

while read_section | sort_section; do :; done

或作为单行:

cat test.txt | while (while read LINE && [ "$LINE" ]; do echo "$LINE"; done) | (read HEADER && (echo "$HEADER"; sort; echo)); do :; done

这篇关于使用命令行工具对行子组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆