4

Find some specific file and then once a file is found, I want some specific word in it and then replace it with finding word with a new one. Can I do it with a single line?

For example, I want to find a file 'file.txt' and in that file want to search read and replace it with write using a single-line command.

  • 1
    Please give a specific example with complete input and desired output. It's hard to understand what you mean if you word it so general. – Byte Commander Sep 27 '16 at 12:08
  • I have edited my question and add what I exactly want . – Avani badheka Sep 27 '16 at 12:12
  • I have tried below answer that work for me – Avani badheka Sep 27 '16 at 13:43
12

Execute:

find -type f -name "specificFileName" -exec sed -i.bak 's/foundWord/replaceWithWord/' '{}' \;

This will only replace first seen 'foundWord' with 'replaceWithWord', in case you wanted to replace all these 'foundWord's add sed's "g" enabler to having replace all seen

find -type f -name "specificFileName" -exec sed -i.bak 's/foundWord/replaceWithWord/g' '{}' \;

note: This will copies the 'specificFileName's as their backup files and name them with "specificFileName.bak", by dropping the "-i.bak" you will tell 'sed' to inplace replace,

  • You should mention that this copies the original file to filename.bak as backup first. But +1 for the correct answer to this originally vague question. – Byte Commander Sep 27 '16 at 12:15
  • Can it changed both the file of the same name in different folder ? – Avani badheka Sep 27 '16 at 12:34
  • I want to say , suppose in a directory there are two folders containing the same file name , then will it affect both of them ? – Avani badheka Sep 27 '16 at 12:45
  • pwd, will print your current path of working directory, if you run this given command in this directory path it will find all "specificFileName" files in current + all sub-directories in each level of depth – αғsнιη Sep 27 '16 at 12:48

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.