Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
566 views
in Technique[技术] by (71.8m points)

linux - Find and replace a particular term in multiple files

How can I replace a particular term in multiple files in Linux?

For instance, I have a number of files in my directory:

file1.txt file2.txt file3.txt

And I need to find a word "searchword" and replace it with "replaceword".

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
sed -i.bak 's/searchword/replaceword/g' file*.txt
# Or sed -i.bak '/searchword/s/searchword/replaceword/g' file*.txt

With bash 4.0, you can do recursive search for files

#!/bin/bash
shopt -s globstar
for file in **/file*.txt
do 
  sed -i.bak 's/searchword/replaceword/g' $file
  # or sed -i.bak '/searchword/s/searchword/replaceword/g' $file
done

Or with GNU find

find /path -type f -iname "file*.txt" -exec sed -i.bak 's/searchword/replace/g' "{}" +;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...