Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and replace text in files in all subdirectories [duplicate]

Tags:

shell

macos

perl

On a Mac; I'm using Hazel to run a shell script, in order to find & replace text in .txt files in multiple subdirectories inside my Downloads folder. My script.sh file lives somewhere else (/Users/admin/Desktop)

script.sh looks like this currently:

#!/bin/bash
cd /Users/admin/Downloads/
perl -pi -w -e 's/OldText/NewText/g;' *.txt

It works, but doesn't look through all the subdirectories inside Downloads. How do I do that?

like image 922
guisauer Avatar asked Oct 15 '25 10:10

guisauer


2 Answers

Use find and xargs

Something similar to (NOT TESTED!):

find /Users/admin/Downloads/ -type f -print0 | xargs -0 perl -pi -w -e 's/OldText/NewText/g;' 

I'm not sure why you would need perl in this case, and I'm not sure who Hazel is and why she would run your shell script, but since you've flagged your question shell and are obviously using bash, I'll provide a shell-only answer. Note that this will work in other shells too, not just bash.

#!/bin/bash

find /Users/admin/Downloads/ -type f -name "*.txt" \
  -exec sed -i '' -e 's/OldText/NewText/g' {} \;

Note that this find command is split into two lines for easier readability. It uses sed instead of perl because sed is smaller and likely faster, and is considered a standard shell tool whereas perl may not be found on all systems.

Note also that the exact syntax of the sed options I've used may depend on the implementation of sed that is on your system.

The find command works like this:

find [path ...] [command ...]

You can man find to see the details, but the command I've provided here does the following.

  • Starts in /Users/admin/Downloads/
  • -type f - Looks for things that are files (as opposed to directories or symlinks)
  • -name "*.txt" - AND looks for things that match this filespec
  • -exec ... - AND executes the following shell command, replacing {} with the filename that's been found.
like image 33
ghoti Avatar answered Oct 17 '25 03:10

ghoti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!