user847988
user847988

Reputation: 984

Unix command sort by number of occurances of a specific character

I have a file with this format:

key value:value:value:value
key value:value
key value
key value:value:value

where there is a key at the first column and in the second a list of values delimited with :. Is there any command that I can sort this file based on the number of occurances of : in the value list i.e. from the most values to least e.g. the previous example will be like this:

key value:value:value:value
key value:value:value
key value:value
key value

Upvotes: 0

Views: 172

Answers (1)

Kent
Kent

Reputation: 195139

quick and dirty:

awk -F: '{$0=NF"#"$0}1' file|sort -nr|sed 's/.*#//' 

test with your example:

kent$  echo "key value:value:value:value
key value:value
key value
key value:value:value"|awk -F: '{$0=NF"#"$0}1'|sort -nr|sed 's/.*#//'
key value:value:value:value
key value:value:value
key value:value
key value

EDIT

the sort tool on linux/unix box is very powerful. but it sorts against column/fields, not based on some calculation. Your requirement needs do calculation first and sort against on the result.

So I just add a new column, which is the count of :, then sort it with sort command, at the end remove that column.

awk adds the column
sort does sort
sed removes that column

you can remove those pipes and see output, then you will see how it worked.

Upvotes: 2

Related Questions