Thursday, 28 May 2020

Find string in all files of all directories, then replace with another string

// replace apple with oranges
1. grep -rl 'apples' /dir_to_search_under | xargs sed -i 's/apples/oranges/g'

// replace ../my_url of all files in the current directory(including sub directories) with ../my_url2

2. grep -rl '../my_url'  | xargs sed -i 's/..\/my_url/..\/my_url2/g'

https://stackoverflow.com/questions/6758963/find-and-replace-with-sed-in-directory-and-sub-directories


grep -r '../my_url' returns all file content in current directory including sub directories that contains "../my_url'

grep -rl '../my_url'  returns all file names  in current directory including sub directories that contains "../my_url'


Xargs is a great command that reads streams of data from standard input, then generates and executes command lines;

 The first example shows how to find out all the .png images and archive them using the tar utility as follows.
Here, the action command -print0 enables printing of the full file path on the standard output, followed by a null character and -0 xargs flag effectively deals with space in filenames.
$ find Pictures/tecmint/ -name "*.png" -type f -print0 | xargs -0 tar -cvzf images.tar.gz
Find Images and Archive Using Tar

https://www.tecmint.com/xargs-command-examples/


sed usage is to search and replace
n basic usage it is used for 'search and replace' with strings.
echo "The quick brown fox jumps over the lazy dog" | sed 's/dog/cat/'
returns
"The quick brown fox jumps over the lazy cat"
Sed really shines when regular expressions are used with it.
You might like to take a look at this article about sed, its quite comprehensive.

No comments:

Post a Comment