$ echo 'foo bar' | sed SOMEMAGIC
boo far
$ echo 'one two' | sed SOMEMAGIC
tne owo
Q: in general, how can I replace the "b" from the "bar" to the "f" of the "foo"? And in reverse too, replace the "f" from the "foo" to the "b" of the "bar".
perlsed
$ echo 'foo bar' | sed SOMEMAGIC
boo far
$ echo 'one two' | sed SOMEMAGIC
tne owo
Q: in general, how can I replace the "b" from the "bar" to the "f" of the "foo"? And in reverse too, replace the "f" from the "foo" to the "b" of the "bar".
Best Answer
You need to make use of capture groups. Capture (1) the first letter of a word, (2) everything until the first letter of the second word, (3) first letter of the second word and swap (3) and (1).
In the examples below, it's assumed that the line starts with a non-blank character
You could say:
or
For example,
The following would also handle cases like spaces at the beginning of the line, and multiple spaces between the two words:
A corresponding perl expression would be:
Examples: