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.

3
  • 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, 2016 at 12:08
  • I have edited my question and add what I exactly want . Sep 27, 2016 at 12:12
  • I have tried below answer that work for me Sep 27, 2016 at 13:43

1 Answer 1

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,

4
  • 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, 2016 at 12:15
  • Can it changed both the file of the same name in different folder ? Sep 27, 2016 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 ? Sep 27, 2016 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 Sep 27, 2016 at 12:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .