Sign up ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free.

Reverse every word of a line using sed


   The job to do is reversing every word of a line.

   that a word is a sequence of lowercase alphabets

   Raw Input

   112358 is a fibonacci sequence...
   a test line
   124816 1392781
   final line...

   Desired Output

   112358 si a iccanobif ecneuqes...
   a tset enil
   124816 1392781
   lanif enil...
share|improve this question

2 Answers 2

up vote 2 down vote accepted

This sed script will do the job:


# Put a \n in front of the line and goto begin.

# Marker for the loop.

# If after \n is a lower case sequence, copy its last char before \n and loop.

# If after \n is not a lower case sequence, copy it before \n and loop.

# Here, no more chars after \n, simply remove it before printing the new line.
share|improve this answer
Nice solution. It works on the example. A word that starts with a capital letter will get all its lower characters reversed. –  McNisse Dec 26 '12 at 10:53
@McNisse: according to the definition of 'word' in the problem, the sequence "Hello" only contain the word "ello", and the sequence "HelloWorld" contains 2 words: "ello" and "orld" (this is my reading of the problem statement, as if we use spaces as word delimiters, "line..." is not a word and should not be reversed). –  jfgagne Dec 26 '12 at 10:58

A tutorial from here is very good. Sample: echo "nixcraft" | rev. And for the SED part, heres from this link.

enter image description here

share|improve this answer
see the raw input clearly. this solution reversing numbers also but I need output as only reversing the lower case characters.. –  user110113 Dec 26 '12 at 9:33
go to 2nd link, you will find all about sed. –  nickanor Dec 26 '12 at 9:45

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.