I'm trying to split a filename consisting of arbitrary number of space-separated words into two separate strings by searching for the first occurrence of a symbol '-', and then switch the order of those strings. For e.g if the filename is originally

word1 word 2 ... word9 - wordA wordB ... wordZ

then the desired output is

wordA wordB ... wordZ - word1 word2 ... word9

Note that there can be more than 1 word on both sides of the '-'. My sed code is

sed -r 's/([a-zA-Z0-9]+) \- ([a-zA-Z0-9])*/\2 \- \1/'

My question is how to specify arbitrary number of words before and after the '-' in sed. I am aware that sed only supports up to 9 patterns.

I've read a past question but the question is about switching a known fixed number of words.


Try this:

echo 'word1 word 2 ... word9 - wordA wordB ... wordZ' | sed 's/\(.*\) - \(.*\)/\2 - \1/'


wordA wordB ... wordZ - word1 word 2 ... word9
| improve this answer | |
  • 1
    It worked. Thank you so much. Now I need to learn what /(.*) means from sed documentation. – Global nomad Jan 30 '16 at 11:26

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.