944,135 Members | Top Members by Rank

Ad:
Sep 7th, 2006
0

Replace text in a file

Expand Post »
Greetings,

Hey guys, I am trying to make a shell script that will scan for a certain 5 lines of text in a file, modify it by adding two lines in the middle and replacing that section of text in the file.

For example read rc.conf for:
Line1
Line2
Line3
Line4
Line5
That match the exact lines

and replace that section or match with

Line1
Line2
INSERTLINE
Line3
INSERTLINE
Line4
Line5

Mainly i am trying to add a new case statment inside an if loop automatically using a shell script. I have tried reading info on awk usage but cannot find anything that matches whta I am trying to accomplish. Any help would be greatly appreciated.

Regards,

S Tompkins
Similar Threads
Reputation Points: 10
Solved Threads: 1
Newbie Poster
toztech is offline Offline
3 posts
since Sep 2006
Sep 7th, 2006
0

Re: Replace text in a file

Here's one way of approaching your problem (pseduo-code):
Shell Scripting Syntax (Toggle Plain Text)
  1. while !eof {
  2. increment fileline
  3.  
  4. while (stillgoing) {
  5. increment index
  6. read line fileline from file
  7. if (compare string to one in database = FALSE)
  8. stillgoing = FALSE
  9. if (index > 5)
  10. insert lines in file
  11. } end while
  12. } end while

Just off the top of my head. Don't take it too literally.
Team Colleague
Reputation Points: 2240
Solved Threads: 338
Vampirical Lurker
John A is offline Offline
5,055 posts
since Apr 2006
Sep 8th, 2006
0

Re: Replace text in a file

awk works for this pretty well -
Shell Scripting Syntax (Toggle Plain Text)
  1. awk '{
  2. print $0
  3. if($0=="Line2") {print "INSERTLINE2"}
  4. if($0=="Line3") {print "INSERTLINE3"}
  5. }' file > newfile
Reputation Points: 62
Solved Threads: 10
Junior Poster
jim mcnamara is offline Offline
179 posts
since May 2004
Sep 11th, 2006
0

Re: Replace text in a file

Shell Scripting Syntax (Toggle Plain Text)
  1. sed '
  2. /Line1/{
  3. N;N;N;N
  4. s/^Line1\nLine2\nLine3\nLine4\nLine5$/Line1\
  5. Line2\
  6. INSERTLINE1\
  7. Line3\
  8. INSERTLINE2\
  9. Line4\
  10. Line5\
  11. /
  12. }' rc.conf
sut
Reputation Points: 20
Solved Threads: 1
Light Poster
sut is offline Offline
30 posts
since Sep 2006

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Shell Scripting Forum Timeline: String Match Comparison
Next Thread in Shell Scripting Forum Timeline: Mail command





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC