0

I have This Code

sed '/Sometexts/ r newtext.txt' old.txt > new.txt

This Replaces The String 'Sometexts' with the contents of text file newtext.txt

but i want to replace on the 2nd occurrence of 'Sometexts' String

How Can i Archive It?

2 Answers 2

1

if the solution is not limited to sed, then awk is your friend, with the following oneliner:

awk 'BEGIN{file="NewText.txt";}{if(/SOMETEX/) count++; if(count==2){while((getline<file)>0) {print};count++;} else print;}' OldText.txt > new.txt

What it does:

awk 'BEGIN{file="NewText.txt";} #sets the path to the 
                                file that will be inserted
{if(/SOMETEX/) count++; #counts occurences of SOMETEX (regex-matching)
 if(count==2) #if we just found the second occurence then
{while((getline<file)>0) {print};count++;}  #read all lines of 
                                             file and print them
else print; #otherwise just print the line
}' 
1

There are many ways to do this.

Probably the simplest is to transform your initial file into a single (very long string) by replacing the newline with another character (I use cap ^ because it is rather harmless in this context), searching for and substituting the n-th occurrence of the search string, and then putting the newlines back in their place.

This can be done with a single command:

 tr '\n' '^' < my_file | sed 's/Sometexts/ r newtext.txt/2' | tr '^' '\n' > new.txt

You can also do it with awk, or on a single line with sed, but it quickly becomes messy.

Edit: if you are scared of using ^, you cand o ti with this single sed command:

 sed ':a;N;$!ba;s/Sometexts/ r newtext.txt/2' file
3
  • if my_file contains any '^' of its own, this will mangle the file with additional newlines...
    – Legionair
    Nov 12, 2013 at 12:30
  • @Legionair you may use another character, or use the new coomand which I added in an Edit to my answer. Nov 12, 2013 at 12:32
  • There is a Problem This Replaces "newtext.txt" as string instead of Text from newtext.txt ????
    – Niresh
    Nov 12, 2013 at 13:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .