How to change file section into each line?

Hi Gurus,
I have below file which has different sections, need to move the sections to beginning of the each record.
original file

[abc_xxxx_yyyy]
aaa
bbb
ccc
[abc_mmmm_nnnn]
ddd
eee
fff

output file.

[abc_xxxx_yyyy] aaa
[abc_xxxx_yyyy] bbb
[abc_xxxx_yyyy] ccc
[abc_mmmm_nnnn] ddd
[abc_mmmm_nnnn] eee
[abc_mmmm_nnnn] fff

thanks in advance

Hello green_k,

On forums, we do encourage users to add their efforts which they have put in order to solve their own problems in their questions. So kindly do so and let us know, since we all are here to learn, cheers.

Thanks,
R. Singh

thanks R.Singh.
I tried to use awk to archive this, but it doesn't work as I have very limited knowledge.
below is my code. my thought is: first read section into ARRAY, then read next line; then print array value and the line together.
my os is: SunOS 5.10 Generic_150400-64 sun4v sparc sun4v

awk '/\[abc*/{a=$0; i++; next}{print a  $0}'

Hello green_k,

Could you please try following.

awk '/^\[/{val=$0;next} {print val,$0}'  Input_file

On Sun o.s use nawk in place of awk .

Thanks,
R. Singh

1 Like

Thanks R.Singh. it works as expected.
one more question, I want to count total number of lines and put total number at end of the record. I don't know how to hold all the lines and print at end of each section. I tried below codes, no luck .
what I thought is to use array line to hold each line, at end, print the line and number. but it doesn't work like that.

please share you suggestion.

awk '/^\[/{val=$0;next} {if(!/^$/) {i++; print val,$0, i}}'
awk '/^\[/{val=$0;next} {if(!/^$/) i++; line=$0}END{if(a in line) print val,line, i}'
awk '/^\[/{val=$0;next} {if(!/^$/) i++; line=$0}END{if(a in line) print val,a, i}' 
[abc_xxxx_yyyy] aaa 3
[abc_xxxx_yyyy] bbb 3
[abc_xxxx_yyyy] ccc 3
[abc_mmmm_nnnn] ddd 3
[abc_mmmm_nnnn] eee 3
[abc_mmmm_nnnn] fff 3

Hello green_k,

Could you please try following.

awk '
/^\[/{
  if(count){
    for(i=1;i<=count;i++){
      print val,a,count
    }
  }
  val=$0
  count=""
  next
}
  {
    a[++count]=$0
  }
END{
  if(count){
    for(i=1;i<=count;i++){
      print val,a,count
    }
  }
}'    Input_file

Thanks,
R. Singh

1 Like

thanks R.Singh. The code works as expected.

:b::b::b: