I'm an avid fan of anime, and typically watch it subtitled. Sometimes the subbers will order the names as if they were Western, putting the given name before the family name. I really don't like this, but manually going through the subtitle file just to reverse the orders of the names would be a waste of time. I'd like to use Awk (or another standard Linux utility if Awk is not the right choice) to search the text for words that start with capital letters and always appear together (bigrams), and reverse their order. Spaces and symbols should be the delimiters for words. This should be sufficient to result in no false positives.

For example, all instances of Miu Matsuoka should be converted to Matsuoka Miu.


Try this,

sed -r -e "s:([A-Z][a-z]+)\s([A-Z][a-z]+):\2 \1:g" subfile > newsubfile

or you can also change the original file as

sed -i -r -e "s:([A-Z][a-z]+)\s([A-Z][a-z]+):\2 \1:g" subfile

The regex ([A-Z][a-z]+)\s([A-Z][a-z]+) selects any 2 consecutive words that start with a capital letter and sed reverses their order. See if this matches all your test cases. I ran some tests and it worked.

  • Regex has always been my weak point, but testing it out, this doesn't seem to work. – forest May 6 at 5:54
  • can you post a small part of your file – Ritajit Kundu May 6 at 5:56
  • Here's what I used to test: paste.debian.net/plain/1081646. The input and output were identical. – forest May 6 at 5:59
  • Check the updated answer. I forgot to put the -r tag in it – Ritajit Kundu May 6 at 6:15
  • Yeah I tried adding -r and adjusting the syntax as well, but must not have done it correctly. – forest May 6 at 6:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.