| xargs -0 sed -i.bak 's/foo/bar/g' Conclusion #Īlthough it may seem complicated and complex, at first, searching and replacing text in files with sed is very simple. type f -name "*.md" -print0 | xargs -0 sed -i 's/foo/bar/g'Ĭommand to recursively find all files containing the search pattern and then pipe the filenames to sed: grep -rlZ 'foo'. If you want to search and replace text only on files with a specific extension, you will use: find. For example, if you are replacing a string in your local git repo to exclude all files starting with dot (. To exclude a directory, use the -not -path option. ![]() type f -print0 | xargs -0 sed -i 's/foo/bar/g' To avoid issues with files containing space in their names, use the -print0 option, which tells find to print the file name, followed by a null character and pipe the output to sed using xargs -0 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.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |