Sorting file contents numerically by field

北城以北 提交于 2020-04-15 19:28:27

问题


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

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.

Example field: daemon:*:1:root

What I'm trying so far:

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

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.


回答1:


You can use sort -t like this:

sort -t : -nk3 /etc/group

-t : tells sort to use field delimiter as :

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



来源:https://stackoverflow.com/questions/32466906/sorting-file-contents-numerically-by-field

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!