0

I have tree of folders inside these folders there are 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 folders then replace the word "date" inside each text file by the word "dating"?

  • almost all the methods are using "sed" and I would like to know how to use "find"! – user88036 Mar 11 '16 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 Mar 12 '16 at 0:00
0

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' {} \;
  • @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 Mar 12 '16 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. – TienPhan Jun 5 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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy