Inserting Text In Specific Location Using Shell Script

Wayne Betts wbetts at bnl.gov
Fri May 26 20:31:02 UTC 2006


Cesar Covarrubias wrote:

>Hello,
>
>I am running a script on about 30 machines and need to insert text after
>a specific comment. For example:
>
>#comment 1
>
>#comment 2
>
>#comment 3
>
>I want to add text after #comment 2, on a new line. I have been trying
>to work with both sed and awk but no success. This has to be done in
>bash or sh and cannot be done in any other language. Any ideas?
>  
>
Here's an example I think would work.  It doesn't require much as far as 
the formatting of the files, other than the form of "#comment 2" which 
could be generalized with some regexp magic, but it sounds like you 
might not need anything so fancy:

Some prerequisites:
a file that contains the text to be inserted (eg. /path/to/insertme.txt)
the file in which the text is to be inserted (eg. /path/to/original.txt)

-----
#!/bin/sh

insertme="/path/to/insertme.txt"
original="/path/to/original.txt"
export INSERT=$insertme  
export ORIGINAL=$original
cat $original | gawk '{print $0; if ($0 == "#comment 2") system("cat 
$INSERT >> $ORIGINAL.mod");}' >> $original.mod
-----

This should produce the file /path/to/original.txt.mod, which you could 
then mv to original.txt, overwriting the original if desired.
(Sorry, I haven't tested this so I may have missed a quote mark or 
something, but that should be close.)

HTH,

- Wayne




More information about the redhat-list mailing list