Reverse words in each line
Have a file of character strings:
Code:
one two three four five Want: Code:
five four three two one Code:
awk '{for (i=NF;i>0;i--) printf("%s ",$i)} {printf("%s","\n")}' $InFile Code:
five four three two one Daniel B. Martin |
Have a look at the rev command. Answered too fast, sorry!
|
Hi.
Here is my attempt in sed: Code:
$ echo 'ab cd ef' | sed -r 's/\w+| +/<&>/g; s/^.*$/\n&\n/;l; :a; s/(\n<[^<>]+>)(.*)(<[^<>]+>\n)/\3\2\1/; l; ta; s/[<>\n]//g' A bit more details: 1) s/\w+| +/<&>/g; -- surround each word and block of spaces by <>. 2) s/^.*$/\n&\n/; -- surround whole line by newlines. 3) In a loop do the following transformation: Code:
\n<word1> ... <word2>\n -> <word2>\n ... \n<word1> BTW, here is my previous attempt :eek: Code:
#!/bin/sed -rf |
[QUOTE=firstfire;4760302]
Code:
sed -r 's/\w+| +/<&>/g; s/^.*$/\n&\n/;l; :a; s/(\n<[^<>]+>)(.*)(<[^<>]+>\n)/\3\2\1/; l; ta; s/[<>\n]//g' The optional l commands help to understand the logic, step-by-step. It will be interesting to see if an awk expert has a solution. Daniel B. Martin |
Code:
awk -F'[ ]' '{for (i=NF;i>0;i--) printf("%s ",$i)} {printf("%s","\n")}' $InFile |
Quote:
Daniel B. Martin |
Quote:
But you knew that because it's your code, right? ;) |
Quote:
I tried to trim one blank from each line by adding a sed following your awk and couldn't make that work. If you can show how to improve your awk that will be appreciated. Daniel B. Martin |
Hey, it's really your awk, here is how to fix it:
Code:
awk -F'[ ]' '{for (i = NF; i > 0; i--) if (i > 1) printf("%s ", $i); else printf("%s\n", $i)}' $InFile |
Quote:
The key to this clever awk is ... Code:
-F'[ ]' Again, thank you for your patience and expertise. Daniel B. Martin |
Quote:
|
Quote:
Daniel B. Martin |
I know you have said you might not be ready for Ruby before, but thought I would show you an alternative:
Code:
ruby -ape 'i=0;$_.chop!.reverse!.scan(/\w+/).each{|x| $_.gsub!(x,$F[i-=1])};$_ += "\n"' file Code:
-ape - a:create fields based on whitespace (default),p:read in each line and print at the end,e:following is script to be run |
[QUOTE=grail;4762240]... thought I would show you an alternative:
Code:
ruby -ape 'i=0;$_.chop!.reverse!.scan(/\w+/).each{|x| $_.gsub!(x,$F[i-=1])};$_ += "\n"' file I hear (and read) about the relative merits of perl, python, and ruby. At some point I will choose one. Daniel B. Martin |
It might be interesting to look at the awk code translated to ruby:
Code:
ruby -pe '$_=$_.chop.split(" ").reverse.join(" ")+"\n"' file Code:
ruby -pe '$_=$_.chop.split(/ /, -1).reverse.join(" ")+"\n"' file |
All times are GMT -5. The time now is 05:33 PM. |