LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (http://www.linuxquestions.org/questions/linux-general-1/)
-   -   search a directory and add file contents when find string (http://www.linuxquestions.org/questions/linux-general-1/search-a-directory-and-add-file-contents-when-find-string-4175444830/)

j-me 01-09-2013 10:06 AM

search a directory and add file contents when find string
 
I have a requirement to insert multiple lines in file(s) that exists in multiple directories. I am thinking that sed or awk would be the best application for this but am stumped on how to accomplish effectively. I prefer sed right now but am open to awk.

requirement:
/DIR1/[multiple directories]
search for <string1>information</string1> when find insert file contents after line.

File contents:
Code:

<properties>
      <Property1>       
      <permission>permission_A</permission>
        <permission>permission_B</permission>
        <permission>permission_C</permission>
  </properties>

What I have tried but failed:
in simplest form:
Code:

sed -i '#<string1>information</string1># -r insert_contents.txt ' config.xml
in a find command
Code:

find /DIR1/Sub_Dir2/config.xml -type f -exec sed -i '#<string1>information</string1># -r insert_contents.txt' {} \;
I recv no errors but no data is inserted.
Thank you.

pan64 01-11-2013 01:56 AM

sorry guy, your find is useless:
find /DIR1/Sub_Dir2/config.xml ..... will find only /DIR1/Sub_Dir2/config.xml (if it was a file), so -exec will work on that single file, which is the same as your previous code (without find).
Also that sed will not insert anything, actually it will do nothing because it is not a valid sed script (contains no sed commands at all).

colucix 01-11-2013 03:29 AM

As pan64 pointed out your sed command is incomplete. Here is a working (?) version:
Code:

find /DIR1 -name config.xml -exec sed -i.bck -r '\@<string1>information</string1>@r insert_contents.txt' {} \;
The sed command to insert the content of a file is r file. Please notice that in order to use a character different than slash in the sed address, you have to put a backslash in front of the address itself (see the part highlighted in red in my example).

Also notice that I used -i.bck to make sed keep a backup copy of the original files. Useful for testing purposes until you're satisfied with the results. Hope this helps.

j-me 01-11-2013 08:54 AM

Thank you both. pan64 ~ I realized after I posted that my find did not perform what I had stated earlier but it was using my isolated test command to prove the sed would work. not exemplifying my entire intent. thank you for pointing that out.
colucix ~ thank you as that was very helpful and proved to work very well.


All times are GMT -5. The time now is 04:22 AM.