简体   繁体   中英

Using bash: how do you find a way to search through all your files in a directory (recursively?)

I need a command that will help me accomplish what I am trying to do. At the moment, I am looking for all the ".html" files in a given directory, and seeing which ones contain the string "jacketprice" in any of them.

Is there a way to do this? And also, for the second (but separate) command, I will need a way to replace every instance of "jacketprice" with "coatprice", all in one command or script. If this is feasible feel free to let me know. Thanks

find . -name "*.html" -exec grep -l jacketprice {} \;

for i in `find . -name "*.html"`
do
  sed -i "s/jacketprice/coatprice/g" $i
done

至于第二个问题,

find . -name "*.html" -exec sed -i "s/jacketprice/coatprice/g" {} \;

Use recursive grep to search through your files:

grep -r --include="*.html" jacketprice /my/dir

Alternatively turn on bash's globstar feature (if you haven't already), which allows you to use **/ to match directories and sub-directories.

$ shopt -s globstar 
$ cd /my/dir
$ grep jacketprice **/*.html
$ sed -i 's/jacketprice/coatprice/g' **/*.html

Depending on whether you want this recursively or not, perl is a good option:

Find, non-recursive:

perl -nwe 'print "Found $_ in file $ARGV\n" if /jacketprice/' *.html

Will print the line where the match is found, followed by the file name. Can get a bit verbose.

Replace, non-recursive:

perl -pi.bak -we 's/jacketprice/coatprice/g' *.html

Will store original with .bak extension tacked on.

Find, recursive:

perl -MFile::Find -nwE '
    BEGIN { find(sub { /\.html$/i && push @ARGV, $File::Find::name }, '/dir'); };
    say $ARGV if /jacketprice/'

It will print the file name for each match. Somewhat less verbose might be:

perl -MFile::Find -nwE '
    BEGIN { find(sub { /\.html$/i && push @ARGV, $File::Find::name }, '/dir'); };
    $found{$ARGV}++ if /jacketprice/; END { say for keys %found }'

Replace, recursive:

perl -MFile::Find -pi.bak -we '
    BEGIN { find(sub { /\.html$/i && push @ARGV, $File::Find::name }, '/dir'); };
    s/jacketprice/coatprice/g'

Note: In all recursive versions, /dir is the bottom level directory you wish to search. Also, if your perl version is less than 5.10, say can be replaced with print followed by newline, eg print "$_\\n" for keys %found .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM