$ 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".


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:

sed 's/\(.\)\([^ ]* \)\(.\)/\3\2\1/'


sed -r 's/(.)([^ ]* )(.)/\3\2\1/'

For example,

$ echo 'foo bar' | sed -r 's/(.)([^ ]* )(.)/\3\2\1/'
boo far
$ echo 'one two' | sed -r 's/(.)([^ ]* )(.)/\3\2\1/'
tne owo

The following would also handle cases like spaces at the beginning of the line, and multiple spaces between the two words:

sed -r 's/([^ ])([^ ]* +)(.)/\3\2\1/'

A corresponding perl expression would be:

perl -pe 's/(\S)(\S+\s+)(\S)/$3$2$1/'


$ echo 'one two' | perl -pe 's/(\S)(\S+\s+)(\S)/$3$2$1/'
tne owo
$ echo 'one two' | perl -pe 's/(\S)(\S+\s+)(\S)/$3$2$1/'
tne owo
$ echo 'foo bar' | perl -pe 's/(\S)(\S+\s+)(\S)/$3$2$1/'
boo far
$ echo '   one     two' | perl -pe 's/(\S)(\S+\s+)(\S)/$3$2$1/'
   tne     owo
  • Maybe you could show the use of word boundary and word character regex logic, it would make the code very much shorter and more readable. – orion Mar 21 '14 at 23:49
one=word ; two=phrase ; three=$one
echo "$one $two"
> pord whrase

A possible solution in awk :

echo 'foo bar' | awk '{x=substr($1,1,1); y=substr($2,1,1); sub(x, y, $1); sub(y, x, $2); print $0}'
boo far

The two substr function calls will extract the first character from each of the records and the two calls to sub function will substitute the first appearance of those characters with each other.


With sed:

echo 'one two' |sed -re 's/([^ ])([^ ]+)( +)([^ ])([^ ]+)/\4\2\3\1\5/'
tne owo

matches also variable spaces.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.