按字段对文件内容进行数字排序 [英] Sorting file contents numerically by field

查看:114
本文介绍了按字段对文件内容进行数字排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写BASH脚本,以根据文件中的特定字段对文件内容进行数字排序.

I am trying to write a BASH script to sort the contents of a file numerically according to a specific field in the file.

文件在/etc/group下.所有字段都用冒号分隔的:.我必须根据第三个字段对/etc/group的内容进行数字排序.

The file is under /etc/group. All of the fields are colon-separated :. I have to sort the contents of /etc/group numerically based on the 3rd field.

示例字段:daemon:*:1:root

到目前为止,我正在尝试什么:

What I'm trying so far:

#!/bin/bash
sort /etc/group -n | cut -f 3-3 -d ":" /etc/group

这真的让我很接近,但是它只打印出第3个字段值的排序列表(因为cut从字面上切掉了该行的其余部分).我正在尝试保留该行的其余部分,但仍按第3个字段的内容对其进行排序.

This is getting me really close, but it only prints out a sorted list of 3rd field values (since cut literally cuts out the rest of the line). I'm trying to keep the rest of the line but still have it sorted by the 3rd field contents.

推荐答案

您可以像这样使用sort -t:

sort -t : -nk3 /etc/group

-t :告诉sort使用字段定界符作为:

-t : tells sort to use field delimiter as :

-nk3告诉sort对字段#3上的数据进行数字排序

-nk3 tells sort to sort data numerically on field #3

这篇关于按字段对文件内容进行数字排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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