Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

Reverse every word of a line using sed

   Description
   -----------

   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
add comment

2 Answers

up vote 2 down vote accepted

This sed script will do the job:

#!/usr/bin/sed

# Put a \n in front of the line and goto begin.
s/^/\n/
bbegin

# Marker for the loop.
:begin

# If after \n is a lower case sequence, copy its last char before \n and loop.
s/\n\([a-z]*\)\([a-z]\)/\2\n\1/
tbegin

# If after \n is not a lower case sequence, copy it before \n and loop.
s/\n\([^a-z]*[^a-z]\)/\1\n/
tbegin

# Here, no more chars after \n, simply remove it before printing the new line.
s/\n//
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
add comment

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
add comment

Your Answer

 
discard

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