Reputation: 10604
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
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
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
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:
-type f
to limit search to files only-regextype
to set regex engine to egrep
(smarter than default emacs)-regex ".*\.(txt|md)"
to limit search to files with txt
or md
extensionfind -print0
and xargs -0
to handle spaces in files names properlyUpvotes: 1