What difference does it make matching a word with/without a trailing whitespace

sedwhitespace

I am learning shell-scripting and for that I am using HackerRank. There is a question related to sed on the same site: 'Sed' command #1:

For each line in a given input file, transform the first occurrence of the word 'the' with 'this'. The search and transformation should be strictly case sensitive.

First of all I tried,

sed 's/the/this/'

but in that sample test case failed. Then I tried

sed 's/the /this /'

and it worked. So, the question arises what difference did the whitespaces created? Am I missing something here?

Best Answer

The difference is whether there is a space after the in the input text.
For instance:

With a sentence without a space, no replacement:

$ echo 'theman' | sed 's/the /this /'
theman

With a sentence with a space, works as expected:

$ echo 'the man' | sed 's/the /this /'
this man

With a sentence with another whitespace character, no replacement will occur:

$ echo -e 'the\tman' | sed 's/the /this /'
the     man
Related Question