Unix command to search and replace text recursively

12,572

Solution 1

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.

Solution 2

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)

Share:
12,572
Chaitanya
Author by

Chaitanya

Updated on July 11, 2022

Comments

  • Chaitanya
    Chaitanya almost 2 years

    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.

  • Chaitanya
    Chaitanya over 10 years
    Thanks Anubhava, why do we need '{}' \; in this command? can you please tell me. Also the command in my question uses -print0 to get the file name, then is that not required in the example you have suggested? Please help me in understanding this.
  • anubhava
    anubhava over 10 years
    Yes -print0 is not required if using my suggested command with -exec option. {} is the placeholder for the filename searched by previous find command. btw -print0 prints the pathname of the current file to standard output, followed by an ASCII NUL character to be piped with xargs -0