2

I have a tree of folders and inside these folders many text files. These files have the same name "log.txt" and the same format. For example inside every file we can see multiple lines like:

date
name
. 
.
.

How can I use the command find to find all the text files "log.txt" in this tree of folders and then replace the word "date" inside each text file by the word "dating"?

2
  • almost all the methods are using "sed" and I would like to know how to use "find"!
    – user88036
    Commented Mar 11, 2016 at 23:56
  • Sure. Are there any flags that can boost its functionality so it can find the files and replace specific words inside these files at once?
    – user88036
    Commented Mar 12, 2016 at 0:00

2 Answers 2

2

Assuming you're currently in the tree root (otherwise replace '.' with the directory name). You can replace 'log.txt' with '*.txt' or whatever you want.

find . -type f -name 'log.txt' -exec sed -i 's/date/dating/g' {} \;
2
  • @Milles. Kindly how can I do it for all the text files at once. Can I do it by replacing 'log.txt' by *.txt ?
    – user88036
    Commented Mar 12, 2016 at 0:10
  • @user88036 sure, you can do it. But you need " ", example "*.txt". Also you can use Operator in find command: Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed.
    – tien
    Commented Jun 5, 2019 at 9:01
1

You can use find and sed, from the root of the directories:

find . -type f -name 'log.txt' -exec sed -i 's/^date$/dating/' {} +
  • find . -type f -name 'log.txt' will find all the log.txt files recursively

  • Within the -exec predicate of find, sed -i 's/^date$/dating/' {} + will replace date in a line of the files with dating, in place.

2
  • Great!!. If I want to run this command on all the text files . Is it correct to replace "log.txt" by " *.txt" ?
    – user88036
    Commented Mar 12, 2016 at 0:03
  • 1
    @goro If the files end in .txt then its correct..
    – heemayl
    Commented Mar 12, 2016 at 0:10

You must log in to answer this question.