ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
#surround line by \n markers
# mark left side of last word or block of spaces by \n:
# \nword1 ... word2\n.. -> \nword1 ... \nword2\n..
# swap the two marked blocks:
# \nword1 ... \nword2\n.. -> word2\n ... \nword1..
s/(\n(\w+| +))(.*)\n((\w+| +)\n)/\4\3\1/
And to assist with understanding (for anyone looking):
-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
i=0 - set counter
$_ - the read line
chop! - remove terminating character (\n)
reverse! - reverse the string (in our case the whole line minus the terminating new line)
scan(/\w+/) - search the string recursively (important!) looking for words and return an array with each index referencing the words found
each - for each element of the array returned from scan perform the following tasks
|x| - variable with the copy of each element stored in it
gsub!(x,$F[i-=1]) - as per awk, find value stored in 'x' and replace with the value stored in global array (created by -a option) starting at the end of the array
and working backwards
$_ += "\n" - re-add the terminating new line character as -p option will print $_'s new value
! - all commands suffixed with '!' means perform this task on the object and make it change the object. Without '!' it will only return a new object with the change performed
That's basically Daniel's initial awk (with the trailing space also fixed), it has the same space collapsing problem. The fix is also the same: split on the regex matching space instead of the character space: