Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Say I have a large plaintext file with a string on every line. The string only consists of alphabetical characters, except for underscores _, which divide the strings in syllables.

I want to sort the text file by the amount underscores in the string. Bonus points for putting every group of X underscores in their own file.

Example:

hel_lo
hi
su_per_u_ser
o_ver_flow

would sort into:

hi
hel_lo
o_ver_flow
su_per_u_ser

I've tried doing this with regex, but I've yet to find a proper way of counting the underscores (regex confuses me thoroughly).

Anyone know how I could handle this?

share|improve this question
up vote 2 down vote accepted

Python makes this easy...

open('out.txt', 'w').write('\n'.join(sorted(open('in.txt'), key=lambda x: x.count('_'))))
share|improve this answer
    
Works like a charm! Removed the \n to get rid of the superfluous empty line. And had to figure out how to run Python scripts as well. Thanks! – SpacyRicochet Oct 21 '13 at 9:44

Simple code in awk:

#!/usr/bin/awk -f

BEGIN   { FS = "_" }        # field separator = syllable separator
        {                   # for each input line
            if(NF > 0)      # if number of syllables > 0
                print $0 > "syllable-"NF".txt"  # print the line to a file
        }

Put the script into a file and then chmod a+x the file. The input can come from stdin or from a file specified as a parameter to the script.

The output will be sorted in files named syllable-x.txt where x is the number of syllables.

share|improve this answer

Even simpler: a bash one-liner:

 cat testfile | while read line; do echo $line >> srt$(echo $line | fgrep -o _ | wc -l).txt ; done 

Output will appear in files called srtN.txt, where N is the number of occurrences of the underscore character in the line.

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .