For example, to search all 3 digit numbers and replace them with the string number you would use: sed -i 's/\b\ Most people use the vertical bar ( |) or colon ( :) but you can use any other character: sed -i 's|/bin/bash|/usr/bin/zsh|g' file.txt 123 Foo foo foo The easier and much more readable option is to use another delimiter character. For example to replace /bin/bash with /usr/bin/zsh you would use sed -i 's/\/bin\/bash/\/usr\/bin\/zsh/g' file.txt If you want to find and replace a string that contains the delimiter character ( /) you’ll need to use the backslash ( \) to escape the slash. In the example below we are using both the g and I flags: sed -i 's/foo/linux/gI' file.txt 123 linux linux linux To make the pattern match case insensitive, use the I flag. sed -i 's/\bfoo\b/linux/g' file.txt 123 Foo linux linux This ensures the partial words are not matched. 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.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |