I'm fairly new to Linux and recently started experimenting with the command line. I decided to make a file and called it 'hi.txt'. The contents of the document was: This is hi.txt.hi hihiI used the command sed -i 's/hi/hotel/g' hi.txt in hopes of making all the 'hi's in the document change to hotel. This was the output:Thotels is hotel.txthotelhotelhotel As you can see, the 'hi' is the word 'This' also got changed. Is there a way to stop this from happening?
How to get the sed command to only search for full words?
text processing;sed
The s/// command expects the search parameter to be a regular expression. Most versions of sed should support the \b match, which is a zero-width match at a word-nonword or a word-edge boundary. Word in this case is defined as a character that is either a letter, digit, or underscore (_). For example, if we assume the string c++ is on a line by itself in your file, \b would match at the following positions:Immediately before the c.Between the c and the first +.Immediately after the last +.The following command should give you the desired results:sed -i 's/\bhi\b/hotel/g' hi.txtThe word this will fail to match because the h is preceded by a word character (t), and the i is followed by a word character (s). However, the string This is hi.txt will match on the second instance of hi, because the surrounding space and . are both non-word characters.