Search pattern and print it on the line before (awk)

Viewed 57

I have this file :

>AX-89948491
CACCTTTT[C/T]ATTTCATTCCTAC
>AX-89940152
AGATGAGA[A/G]TAAAGCTTCTGTC
>AX-89922107
ACAGAAAT[G/T]TATAGATATTACT

I need to find the pattern "[A-Z]/[A-Z]" (it is necessarily present every two lines) ; and put it on the line before like this :

>AX-89948491-[C/T]
CACCTTTT[C/T]ATTTCATTCCTAC
>AX-89940152-[A/G]
AGATGAGA[A/G]TAAAGCTTCTGTC
>AX-89922107-[G/T]
ACAGAAAT[G/T]TATAGATATTACT

I did :

awk 'tmp=/\[[A-Z]\/[A-Z]]/{if (a && a !~ /\[[A-Z]\/[A-Z]]/) print a"-"$tmp; print} {a=$0}' my_file

But that gives the entire line , not the pattern.

Any help?

2 Answers

You could print the previous line plus the current matched part of the pattern, and given that it is present every 2 lines:

awk '
match($0, /\[[A-Z]\/[A-Z]]/) {
  m = substr($0, RSTART, RLENGTH)
  print prev "-" m ORS $0
}
{prev = $0}
' my_file

Output

>AX-89948491-[C/T]
CACCTTTT[C/T]ATTTCATTCCTAC
>AX-89940152-[A/G]
AGATGAGA[A/G]TAAAGCTTCTGTC
>AX-89922107-[G/T]
ACAGAAAT[G/T]TATAGATATTACT

With your shown samples only, please try following awk program. Here is tac + awk + tac solution. Simple explanation would be using tac to print output in reverse lines order(from bottom to up) sending it to awk program to get [[A-Z]/[A-Z] and saving its matched value to val variable and printing that line, if match function doesn't have any matched regex value then printing that line(basically lines where we need to add [[A-Z]/[A-Z] value) along with - and val value. Now passing this output to tac again to get output in exact same format in which OP has shown us samples.

tac Input_file | 
awk '
  match($0,/\[[A-Z]\/[A-Z]]/){
    val=substr($0,RSTART,RLENGTH)
    print
    next
  }
  {
    print $0"-"val
  }
' | tac
Related