Paranrax
Paranrax

Reputation: 131

Getting 3 string before and after of each characters using awk

What I have expected is the output like below:

[before character h is null and assign with '#". After character h are "e","l","l".]

[before character e is "h". After character e are "l","l","o".]

[before character l are "h" and "e". After character l are "l" and "o".]

[before character l are "h" and "e". After character l are "l" and "o".]

[before character l are "h","e","l". After character l is "o".]

[before character o are "e","l","l". After character o is null and assign with '#".]

# # # h e l l  
# # h e l l o  
# h e l l o #  
h e l l o # #  
e l l o # # # 

# # # w o n d
# # w o n d e
# w o n d e r
w o n d e r f
o n d e r f u
n d e r f u l
d e r f u l #
e r f u l # #
r f u l # # # 

Input file:

h e l l o

w o n d e r f u l

Code:

awk -v s1="# # #" 
'BEGIN{v=length(s1)}
      {$0=s1 $0 s1;num=split($0, A,"");
         for(i=v+1;i<=num-v;i++){
            q=i-v;p=i+v;
         while(q<=p){
            Q=Q?Q OFS A[q]:A[q];q++
         };
      print Q;Q=""
      }
}' InputFile

But the result I got is:

#   #   # h   e   l  
  #   # h   e   l   l
#   # h   e   l   l  
  # h   e   l   l   o
# h   e   l   l   o #
h   e   l   l   o #  
  e   l   l   o #   #
e   l   l   o #   #  
  l   l   o #   #   #

#   #   # w   o   n  
  #   # w   o   n   d
#   # w   o   n   d  
  # w   o   n   d   e
# w   o   n   d   e  
w   o   n   d   e   r
  o   n   d   e   r  
o   n   d   e   r   f
  n   d   e   r   f  
n   d   e   r   f   u
  d   e   r   f   u  
d   e   r   f   u   l
  e   r   f   u   l #
e   r   f   u   l #  
  r   f   u   l #   #
r   f   u   l #   #  
  f   u   l #   #   #

How to solve it? Please guide me. Thanks

Upvotes: 0

Views: 75

Answers (1)

Ed Morton
Ed Morton

Reputation: 204015

Add gsub(/ /,"") to the top of @fedorqui's answer to your previous question, change ## to ### and change 5 to 7 and you get:

$ cat tst.awk
{
    gsub(/ /,"")
    n=length($0)
    $0 = "###" $0 "###"
    gsub(/./, "& ")
    for (i=1; i<=2*n; i+=2)
        print substr($0, i, 7*2-1)
    print ""
}

$ awk -f tst.awk file
# # # h e l l
# # h e l l o
# h e l l o #
h e l l o # #
e l l o # # #


# # # w o n d
# # w o n d e
# w o n d e r
w o n d e r f
o n d e r f u
n d e r f u l
d e r f u l #
e r f u l # #
r f u l # # #

Upvotes: 1

Related Questions