Thread: Visit recursively all files in a folder and insert a specific string

  1. #1
    Registered User Hannibal2010's Avatar
    Join Date
    Jun 2011
    Location
    Hanoi, Vietnam
    Posts
    46

    Visit recursively all files in a folder and insert a specific string

    Dear all,

    I have the question that:

    I have a directory in Linux, call it: test_directory.
    This directory has files and sub-directories. (only text files)
    Text file CAN contains the specific string, for example, MY_STRING_1
    For example, one line in one text file maybe:
    MY_STRING_1 abc xyz blah blah //MY_STRING_1 is not single word in one line.

    Now, I want to access ALL files in this directory (include sub-directories) and after each MY_STRING_1, add MY_STRING_2 as new line.
    For example:
    Code:
    MY_STRING_1 blah blah blah
    abc xyz
    will become
    Code:
    MY_STRING_1 blah blah blah
    MY_STRING_2
    abc xyz
    Please give me a help. I am using Linux environment

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Code:
    $ cat baz.c
    MY_STRING_1 blah blah blah
    abc xyz
    $ sed -e '/MY_STRING_1/ahello' baz.c
    MY_STRING_1 blah blah blah
    hello
    abc xyz
    Now combine that with say 'find' to find all the text files in a directory, and wrap it up with something looking like

    mv file tmp
    sed ... tmp > file
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User Hannibal2010's Avatar
    Join Date
    Jun 2011
    Location
    Hanoi, Vietnam
    Posts
    46
    Dear Salem,

    I tried your guide.

    It can displays my expected result into the screen, but nothing happens with the real file

  4. #4
    Registered User Hannibal2010's Avatar
    Join Date
    Jun 2011
    Location
    Hanoi, Vietnam
    Posts
    46
    I think I found it

    Code:
    find ./ -type f | xargs sed -i '/MY_STRING_1/aMY_STRING_2'

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 03-10-2011, 12:43 PM
  2. How to lock specific drive or folder or file?
    By chottachatri in forum C# Programming
    Replies: 11
    Last Post: 08-08-2009, 03:42 PM
  3. How to get names of folders in specific folder
    By bikr692002 in forum Windows Programming
    Replies: 17
    Last Post: 09-04-2006, 02:57 PM
  4. Encrypting a specific folder.
    By nextstep in forum C++ Programming
    Replies: 2
    Last Post: 03-28-2005, 07:47 AM
  5. Console App., Hide specific folder
    By nextstep in forum C++ Programming
    Replies: 10
    Last Post: 03-28-2005, 05:28 AM