Home > Back-end >  Check if line starts with AND next line too bash
Check if line starts with AND next line too bash

Time:03-15

I have a while with an if condition that checks if my line starts with a specific string :

while read line; do
# reading each line
if [[ $line == P0* ]]
 then
   echo $line
fi

I want to add a condition to be sure that the next line after my "P0*" line doesn't contain a specific string : "PIC S9".

For example for this source :

P00001     05 ID-TECH-DPR
              PIC S9(9) COMP.
P00005     05 ID-TECH-INDV
              PIC S9(9) COMP.
P00009     05 CO-REG-LIQ PIC X(1).
P00010     05 NO-INST-LIQ PIC X(3).
P00013     05 NO-ORD-DPR

I need my output to be :

P00009     05 CO-REG-LIQ PIC X(1).
P00010     05 NO-INST-LIQ PIC X(3).
P00013     05 NO-ORD-DPR

Instead of :

P00001     05 ID-TECH-DPR
P00005     05 ID-TECH-INDV
P00009     05 CO-REG-LIQ PIC X(1).
P00010     05 NO-INST-LIQ PIC X(3).
P00013     05 NO-ORD-DPR

CodePudding user response:

I would do it with AWK. Try:

#!/bin/bash
awk '
  (s != ""){if ($0 !~ /PIC S9/) {print s}; s=""}
  /^P0/{s=$0}
' srce

supposing the file srce contains:

P00001     05 ID-TECH-DPR
              PIC S9(9) COMP.
P00005     05 ID-TECH-INDV
              PIC S9(9) COMP.
P00009     05 CO-REG-LIQ PIC X(1).
P00010     05 NO-INST-LIQ PIC X(3).
P00013     05 NO-ORD-DPR

CodePudding user response:

Unless you actually need to address each line in bash for another reason, just do

grep ^P0 my-file | grep -v '^[[:space:]]*PIC S9'

Or in awk, you can do the same, but also address each line in awk:

awk '/^P0/ && !/^[[:space:]]*PIC S9/' my-file

In bash you can add a second test, but bash regex is slow:

if [[ $line == P0* && ! $line =~ ^[[:space:]]*PIC\ S9 ]]
then
  • Related