basheps
basheps

Reputation: 10604

Replace text in multiple file extentions

I'm trying to replace some text in several files using sed.

For example: replacing lion with hawk in all txt and md files within a directory and its subdirectories.

So far I have from research the best (non-working) attempt I have is:

find . -type *.txt | xargs sed -i '' 's/lion/hawk/'

Also trying to add md to txt regex - *\.(txt|md) gives an error.

Thanks in advance for any help.

Upvotes: 0

Views: 70

Answers (3)

beerbajay
beerbajay

Reputation: 20270

You want

find . -type f \( -name '*.txt' -o -name '*.md' \) -exec sed -i 's/lion/hawk/g' {} \;

The -o is a logical OR on the two -name predicates. You can also directly use -exec instead of piping to xargs (both work).

edit updated quoting & parens.

Upvotes: 6

Avinash Raj
Avinash Raj

Reputation: 174696

Give a try to the below GNU find command,

find . -name *.txt -o -name *.md -type f | xargs sed -i 's/lion/hawk/g'

Explanation:

.                              #  Current directory

-name *.md -o -name *.md       # Filenames end with .txt or .md
-type f                        #   Only files.
xargs sed -i 's/lion/hawk/g'    #  Replace lion with hawk on the founded files.

Upvotes: 0

mvp
mvp

Reputation: 116068

This should work for you:

find . -type f -regextype egrep -regex ".*\.(txt|md)" -print0 | xargs -0 sed -i '' 's/lion/hawk/'

Important differences from your attempt:

  • use -type f to limit search to files only
  • use -regextype to set regex engine to egrep (smarter than default emacs)
  • use -regex ".*\.(txt|md)" to limit search to files with txt or md extension
  • use find -print0 and xargs -0 to handle spaces in files names properly

Upvotes: 1

Related Questions