user1081596
user1081596

Reputation: 907

A quick way to revert words in sentence in unix?

I need something which reverts words in a sentence in opposite order. I am sure it is possible to do without writing a script.

Something which receives an input stream like echo AAaa BBbb CCcc | foo and prints CCcc BBbb AAaa

Sorry, I changed the example, the words themselves should not be reverted. So, rev does not work

Upvotes: 0

Views: 333

Answers (6)

jfg956
jfg956

Reputation: 16750

A cryptic version usind sed, working on multi-line input, and spaces between words and at the beginning/end of the line:

echo -e "  AAaa     BBbb CCcc\nZ Y X" | sed -e 'G;:a;s/^\([^ ]*\) \(.*\)\n\(.*\)$/\2\n \1\3/;ta;s/\n//'

What it does is:

  1. Append a new line at the end of the line (the G command),
  2. Put the 1st word just after the newline (the big s command),
  3. Loop to previous as long as there are words,
  4. Remove the new line between the last word (that is now the 1st) and the rest of the sentence.

Upvotes: 1

jfg956
jfg956

Reputation: 16750

In pure bash, so without needing a subprocess, and working on multi-line input like the awk solution, but not working if many spaces between words of at the beginning/end of the line :-(:

function revert_line_in() {
  test $# -eq 0 && return
  test $# -eq 1 && echo -n "$1"
  test $# -eq 1 || { local word=$1; shift; revert_line_in $@; echo -n " $word"; }
}

function revert_line() {
  while read line; do revert_line_in $line; echo; done
}

echo -e "    AAaa   BBbb CCcc\nthis is another test example" | revert_line

revert_line <<< "AAaa BBbb CCcc
this is another test example"

revert_line < file

Note the local keyword in the function that declare local variable. If omitted, the solution breaks.

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 246827

echo AAaa BBbb CCcc | tr ' ' '\n' | tac | tr '\n' ' '

Upvotes: 4

zeroos
zeroos

Reputation: 2204

sure there is, its rev:

~ $ echo AAA BBB CCC DDD | rev
DDD CCC BBB AAA
~ $ 

EDIT:

Ok, so you may also try using tac this way:

~ $ echo -n "AAaa BBbb CCcc DDdd " | tac -s ' '
DDdd CCcc BBbb AAaa ~ $

The only problem is it doesn't display new line at the end of the string.

Upvotes: 5

Kent
Kent

Reputation: 195079

well when I saw this question, I thought tac or rev too. however I guess OP made a bad example with AAA BBB. he may want to revert "word"s but not all characters.

see this, if it is what you want:

kent$  echo "this is another test example"|awk '{for(i=NF;i>0;i--)printf $i" "}'
example test another is this      

Upvotes: 6

DonCallisto
DonCallisto

Reputation: 29922

tac AAAA BBBB CCCC

Try that one!

Upvotes: 2

Related Questions