sed first and last patten in a file?

January 14, 2011 at 07:18:26
Specs: Linux/Unix/solaris
Hi programmers!

I tried a lot with sed but unfortunaly without any success. My examplefile.txt should be changed with a inserted "BEGIN" before a first pattern (here: the the line which is positioned at the first point) and a "END" after a last pattern (here: the last blanc line).

e.g.
demofile.txt: ...

<tab> third lineblabla
<tab> fourth lineblabla
block2
<tab> first lineblabla
<tab> second lineblalba
<tab> third lineblabla
<tab> fourth lineblabla
<space>
block3
<tab> first lineblblb
<tab> second lineblabla
<tab> third lineblblb
<space>
block4
<tab> first lineblabla
<tab> second lineblabla
<END OF FILE>

.. will become
demofile.txt:

<tab> third lineblabla
<tab> fourth lineblabla
BEGIN
block2
<tab> first lineblabla
<tab> second lineblalba
<tab> third lineblabla
<tab> fourth lineblabla
<space>
block3
<tab> first lineblblb
<tab> second lineblabla
<tab> third lineblblb
END
<space>
block4
<tab> first lineblabla
<tab> second lineblabla
<END OF FILE>


See More: sed first and last patten in a file?

Report •

#1
January 17, 2011 at 11:25:23
If I were a better sed programmer, maybe I could provide a solution. I am not so I have provided a 2-pass awk solution. The first pass determines at what position BEGIN and END should be and outputs the data to a position file, and the second pass reads the position file into an array, and prints out the data:

# first pass: find out the positions in the demofile the tags belong
rm -f position.txt
awk ' BEGIN { stop_flag=1 }
{
if($1 ~ /block/ && stop_flag == 1)
   {
   print NR >> "position.txt"
   stop_flag=0
   }

if(NF == 0)
   line=NR

}
END { print line >> "position.txt"
} ' demofile.txt

# second pass: print out the positions
awk ' BEGIN {
  cnt=0
  while ( getline < "position.txt" > 0 )
      {
      cnt++
      if(cnt==1)
         myarr[$0]="BEGIN"
      if(cnt==2)
         myarr[$0]="END"
      }

}
{
if(NR in myarr)
   printf("%s\n", myarr[NR])

printf("%s\n", $0)

} ' demofile.txt


Report •
Related Solutions


Ask Question