Results 1 to 5 of 5

Thread: Find string inside files and replace with a new string

  1. #1
    Join Date
    Jun 2020
    Beans
    3

    Lightbulb Find string inside files and replace with a new string

    Hi there,
    I need to find all files containing certain text inside my project directory.
    This includes sub-directories.

    I've managed to find all the files:

    Code:
    find . -type f -exec grep -H 'Rename' {} \;


    Now I need to replace the keyword "Rename" with "XYZ" leaving the rest of text in each file intact.

    Ideas?
    Attached Images Attached Images

  2. #2
    Join Date
    Aug 2011
    Location
    52.5° N 6.4° E
    Beans
    6,853
    Distro
    Xubuntu 22.04 Jammy Jellyfish

    Re: Find string inside files and replace with a new string

    sed is the most commonly used tool for such text replacements. Ask your favourite search engine for a tutorial and experiment a bit in a test directory.

  3. #3
    Join Date
    Jun 2020
    Beans
    3

    Re: Find string inside files and replace with a new string

    I understand how sed works: sed -i s/text/replacement/g
    However - I do not understand how to plug it in a loop so it automatically alters a files that has been found by "find"

    Ideas?

  4. #4
    Join Date
    Dec 2014
    Beans
    2,721

    Re: Find string inside files and replace with a new string

    Why don't you just replace the 'grep' command in the 'find' with 'sed' ? Like so:
    Code:
    find . -type f -exec sed -i 's/text/replacement/g' \{\} \;
    You might want to do a test-run without the '-i' to see what it will do (without '-i' or '--in-place' 'sed' will just output the result of it's editing to standard out), probably piping the output to 'less'.

    Holger

  5. #5
    Join Date
    Jun 2020
    Beans
    3

    Re: Find string inside files and replace with a new string

    Great.
    This works.
    Thank you

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •