Obtaining desired output can be done in several different ways. Perl and Awk presented below work in exactly same manner. You can redirect either command using >
operator to file and then use grep -f pattern.txt data.txt
For instance, with perl presented below, we can do:
perl -ne '@s=split /[KR ]/,$_; foreach(@s){ print "$_\n" if !/^$/}' input.txt > pattern.txt && grep -f pattern.txt data.txt
Perl
The perl approach is effectivelly the same as AWK explained below: split line into columns using K,R, and space as separators then iterate over all of them printing only non-empty columns.
$ perl -ne '@s=split /[KR ]/,$_; foreach(@s){ print "$_\n" if !/^$/}' input.txt
MSTNP
PQ
T
NTN
PE
DV
FPGGQI
AWK
$ awk -F '[KR ]' 'BEGIN{OFS="\n"};{$1=$1;print}' input.txt | awk '!/^$/'
MSTNP
PQ
T
NTN
PE
DV
FPGGQI
Key points of how this works:
-F
allows us to use space,K and R as separators for columns(aka fields).
BEGIN{OFS="\n"}
allows us to use newline as output separator so that the items come out separated by newline
- To apply the new OFS we trigger rebuilding of text line via
$1=$1
assignment, and finally print the line.
- due to multiple column separators K,R, and space being adjacent (for example in
PQRK
) we have to filter out empty lines from the first awk, which is what the second awk is doing.