Search code examples
bashawksedtail

How to use awk to select text from a file starting from a line number until a certain string


I have this file where I want to read it starting from a certain line number, until a string. I already used

awk "NR>=$LINE && NR<=$((LINE + 121)) {print}" db_000022_model1.dlg

to read from a specific line until and incremented line number, but right now I need to make it stop by itself at a certain string in order to be able to use it on other files.

DOCKED: ENDBRANCH   7  22
DOCKED: TORSDOF 3
DOCKED: TER
DOCKED: ENDMDL

I want it to stop after it reaches

DOCKED: ENDMDL

#!/bin/bash

# This script is for extracting the pdb files from a sorted    list of scored
# ligands

mkdir top_poses

for d in $(head -20 summary_2.0.sort | cut -d, -f1 | cut -d/ -f1)
    do
    cd "$d"||continue
    # find the cluster with the highest population within the dlg
    RUN=$(grep '###*' "$d.dlg" | sort -k10 -r | head -1 | cut -d\| -f3 | sed 's/ //g')
    LINE=$(grep -ni "BEGINNING GENETIC ALGORITHM DOCKING $RUN of 100" "$d.dlg" | cut -d: -f1)
    echo "$LINE"
    # extract the best pose and correct the format
    awk -v line="$((LINE + 14))" "NR>=line; /DOCKED: ENDMDL/{exit}" "$d.dlg" | sed 's/^........//' > "$d.pdbqt"

    # convert the pdbqt file into pdb
    #obabel -ipdbqt $d.pdbqt -opdb -O../top_poses/$d.pdb
    cd ..
    done 

When I try the

awk -v line="$((LINE + 14))" "NR>=line; /DOCKED: ENDMDL/{exit}" "$d.dlg" | sed 's/^........//' > "$d.pdbqt"

Just like that in the shell terminal, it works. But in the script it outputs an empty file.


Solution

  • Depending on your requirements for handling DOCKED: ENDMDL occurring before your target line:

    awk -v line="$LINE" 'NR>=line; /DOCKED: ENDMDL/{exit}' db_000022_model1.dlg
    

    or:

    awk -v line="$LINE" 'NR>=line{print; if (/DOCKED: ENDMDL/) exit}' db_000022_model1.dlg