1

I am using the following command

find . -type f -exec sed -i 's/_backpack.html/_backpack_cal.html/g' {} +

I expect all "_backpack.html" strings in my project to be replaced to _backpack_cal.html and this happens.

However, the problem is that it also edits my .git directory which corrupts git. How can I prevent find from touching my .git directory at the same time working with all the other sub-directories

  • Do you want to omit files in a .git directory only, or do you want to omit all hidden files, which traditionally means all files beginning with "." and all files under directories that begin with "." ? – Mark Plotnick Jun 3 '15 at 17:16
  • For the problem I was facing I just wanted to omit .git – Nirvedh Meshram Jun 3 '15 at 23:14
4

You could use :

find . -name .git -prune -o -type f -exec sed -i 's/_backpack.html/_backpack_cal.html/g' {} +

I added the -name .git -prune section which basically means "if the name of the directory is .git, do not process that directory."

Also, please note the added -o (meaning or) which only executes your statement if the first one is false (ie if the name of the processed file is the .git directory).

Of course, you should test this before actually executing the command, by replacing the -exec ... part with a -print, for example.

  • The parentheses are actually optional here. – Gilles 'SO- stop being evil' Jun 3 '15 at 21:51
  • @Gilles You are right, the and (default) has precedence over the or, I'll change it. – user43791 Jun 3 '15 at 22:03
0

If you want to exclude .git only:

find . ! -path '.git/*' -type f

To exclude all hidden files and directories:

find . ! -path '*/.*' -type f
0

Add:

! -regex '.*/\.git/.*'

to skip occurrences of .git and its contents in all subdirectories:

find . -type f ! -regex '.*/\.git/.*' -exec sed -i 's/_backpack.html/_backpack_cal.html/g' {} +
  • The ! negates the expression that follows.
  • The .*/\.git/.* regular expression matches files whose path contains /.git/.

(As a best practice, before trusting my suggestion check that it actually skips the .git directory, for example replacing sed with an innocuous ls:

find . -type f ! -regex '.*/\.git/.*' -exec ls -l {} \; | less

)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.