Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unix command to search and replace text recursively [closed]

I am looking for a UNIX command that helps me to search for a text from all the files in a folder recursively and replace it with new value. After searching in internet I came across this command which worked for me.

find ./myFolder -type f -print0 | xargs -0 sed -i 's/Application/whatever/g'

Please help me in understanding the above command. I was not able to understand this part of the command : -print0 | xargs -0, what this indicates? I know only basics in Unix so finding it difficulty in understanding this. I am using bash shell.

Also are there any alternate commands that provides same functionality in Unix, from google searching I got commands related to Perl scripting, I don't know Perl so dropped the idea of using it.

like image 601
Chaitanya Avatar asked Jan 03 '14 12:01

Chaitanya


2 Answers

Also are there any alternate commands that provides same functionality in Unix

Yes you can do all this in find itself:

find ./myFolder -type f -exec sed -i 's/Application/whatever/g' '{}' \;

-exec option in find is for:

-exec utility [argument ...] ;
True if the program named utility returns a zero value as its exit status. Optional arguments may be passed to the utility. The expression must be terminated by a semicolon ('';''). If you invoke find from a shell you may need to quote the semicolon if the shell would otherwise treat it as a control operator. If the string ''{}'' appears anywhere in the utility name or the arguments it is replaced by the pathname of the current file. Utility will be executed from the directory from which find was executed. Utility and arguments are not subject to the further expansion of shell patterns and constructs.

like image 60
anubhava Avatar answered Oct 04 '22 11:10

anubhava


find is passing through all file from a given path -type f limite to file (no folder, ...) -print0 give the output to stdout with corresponding file

so this give you all file from a starting point and all subfolder inside

xargs allow you to pass parameter to next command coming from previous one (so the file name here)

sed -i edit the input (here the passed file) 's/Application/whatever/g' sed command that replace the pattern "Application" by "whatever", on any occurence (g)

like image 37
NeronLeVelu Avatar answered Oct 04 '22 13:10

NeronLeVelu