2

I have several lines in file, just like below:

/adbc/eee/ddd/baa/ /adbc/fff/ddd/ccc/avfff/ /adbc/ccc/ddd/b/ /adbc/fff/ddd/c/ /adbc/ccc/ddd/bf/ /adbc/ccc/ddd/bc/ 

The sort algorithm must first get the string before last /, that is:

baa avfff b c bf bc 

and then sort it by the first character, and then the length of the string, and then alphabetically.

The expected result is

/adbc/fff/ddd/ccc/avfff/ /adbc/ccc/ddd/b/ /adbc/ccc/ddd/bc/ /adbc/ccc/ddd/bf/ /adbc/eee/ddd/baa/ /adbc/fff/ddd/c/ 
1
  • 1
    You don't sort with bash. Surprisingly enough, you sort with sort :-) Commented Nov 13, 2013 at 2:46

2 Answers 2

3

You could use in a pre-processing step to add 3 columns all based on the field of the interest, feed to sort, then use cut to discard the extra fields

awk -F'/' -v OFS="/" '{x=substr($(NF-1), 1, 1); print(x, length($(NF-1)), $(NF-1), $0)}' file.txt | sort -k1,1 -k2,2n -k3,3 -t'/' | cut -f4- -d'/' /adbc/fff/ddd/ccc/avfff/ /adbc/ccc/ddd/b/ /adbc/ccc/ddd/bc/ /adbc/ccc/ddd/bf/ /adbc/eee/ddd/baa/ /adbc/fff/ddd/c/ 
Sign up to request clarification or add additional context in comments.

Comments

1
cat sortthisfile | while read line do field=$( echo $line | sed -e 's:/$::' -e 's:.*/::' ) firstchar=${field:0:1} fieldlen=${#field} echo "${firstchar},${fieldlen},${field},${line}" done | sort-k1,1 -k2,2n -k3,3 -t, | sed 's:.*,/::' 

Obviously, sortthisfile is the name of your file.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.