


If this is not the wanted behavior, use the word-boundary expression ( \b) at both ends of the search string. With the global replacement flag sed replaces all occurrences of the search pattern: sed -i 's/foo/linux/g' file.txt 123 Foo linux linuxĪs you might have noticed, the substring foo inside the foobar string is also replaced in the previous example. If the g flag is omitted, only the first instance of the search string in each line is replaced: sed -i 's/foo/linux/' file.txt 123 Foo linux foo Let’s see how we can use the sed command to search and replace text in files with some of its most commonly used options and flags.įor demonstration purposes, we will be using the following file: It is a good practice to put quotes around the argument so the shell meta-characters won’t expand. INPUTFILE - The name of the file on which you want to run the command.When the replacement flag is provided, all occurrences are replaced. By default, sed reads the file line by line and changes only the first occurrence of the SEARCH_REGEX on a line. SEARCH_REGEX - Normal string or a regular expression to search for.It can be any character but usually the slash ( /) character is used. s - The substitute command, probably the most used command in sed.If an extension is supplied (ex -i.bak), a backup of the original file is created. This option tells sed to edit files in place. -i - By default, sed writes its output to the standard output.Sed -i 's/SEARCH_REGEX/REPLACEMENT/g' INPUTFILE
