Articles

How to insert string in a list?

September 19, 2005 at 16:18:32
Specs: Solaris, 2GB

Hi Folks,

Is there a way to insert a string of text in a database list by first locating a specific word and then inserting (or appending) a string every 3rd line after it. I've tried it with sed with limited success. The "word appears in several blocks of text; I wish to insert the string in each block on the 3rd line.

Thanks for your help in advance.


See More: How to insert string in a list?

Report •


#1
September 19, 2005 at 20:19:20

How are you defining a "block" of text? Do you want to modify only every 3rd line?

You might want to submit a sample file.


Report •

#2
September 20, 2005 at 07:26:14

Hi Nils,

Yes, here's an example. I'm trying to locate the word "Word1" for each block as such:


Word1 AAAAAAAAAAAAAA {
BBBBBBBBBBBBBB
CCCCCCCCCCCCCC
DDDDDDDDDDDDDD
}


Word1 BBBBBBBBBBBBB {
ZZZZZZZZZZZZZ
WWWWWWWWWWWWW
QQQQQQQQQQQQ
}


Word12 AAAAAAAAAAAAA {
BBBBBBBBBBBBB
CCCCCCCCCCCCC
DDDDDDDDDDDDD
}


I would like locate each block above by the word "Word1" and then insert a string of text (Ts) in the 4th line of each block as such:

Word1 AAAAAAAAAAAAAA {
BBBBBBBBBBBBBB
CCCCCCCCCCCCCC
DDDDDDDDDDDDDD
TTTTTTTTTTTTTT
}


Word1 BBBBBBBBBBBBBB {
ZZZZZZZZZZZZZZ
WWWWWWWWWWWWWW
QQQQQQQQQQQQQQ
TTTTTTTTTTTTTT
}


Thanks for your help.


Report •

#3
September 20, 2005 at 09:30:32

I'm trying to identify a pattern. Does 'Word1' always start at the beginning of the line in line 1 of the block?

Can we search just for 'Word1' at the beginning of the line and not worry about whether it's the first line of the block?


Report •

Related Solutions

#4
September 20, 2005 at 10:52:57

Yes, the word "word1" starts at the beginning of each block (as a reference point). From the reference point one, a string is inserted on the 4th line within the "{ }". The reason for this is that there are other blocks that start with a "word" and a number, like word12, word45, wordxy, etc. I want to target a specific word, in this case "word1".

Thanks.


Report •

#5
September 20, 2005 at 11:31:27

Here's an awk script that prints the line of TTTs after the 4th line if the beginning of the line matches "Word1":

#!/bin/ksh

awk ' BEGIN { allt="TTTTTTTTTTTTTTTTT"; cnt=0; prn=0 }
{
if($0 ~ /^Word1/)
prn=1

if(prn == 1)
cnt++

printf("%s\n", $0)
if(prn == 1 && cnt == 4)
{
prn=0
cnt=0
printf("%s\n", allt)
}

} ' datafile.txt > newdatafile.txt



Report •

#6
September 20, 2005 at 12:06:42

Nils,

It's perfect!

Thanks a bunch....


Report •


Ask Question