Nested Loops for text file

Hi

A text file containing data something like

Vehicle: BMW Class
checkin_note: 
Tyre   : Four
path_id   : 11
vault_file_size: -1

Vehicle: Toyota Class
checkin_note: 
Tyre   : Four
path_id   : 11
vault_file_size: -1

Vehicle: Chevrolet Class
checkin_note: 
Tyre   : Five
path_id   : 11
vault_file_size: -1

If Tyre = Four then Print Vehicle i.e. BMW/Chevrolet/Toyota

Can you post what you have tried?

FilePath=("test_result.txt")
for Path in "${FilePath[@]}"
do
	for((j = i; j <= 5; j++));
	do
	Line=$(grep -n 'Tyre : Four' test_result.txt | cut -d : -f1)
	awk '{if (NR=='$Line'-2) print}' test_result.txt
	done
done
$ awk -v Tyre='Four' ' $0 ~ /Vehicle:/ { veh=$0 } $0 ~ "Tyre : "Tyre { print veh } ' file
> Vehicle: BMW Class
Vehicle: Toyota Class
1 Like

Hi Anbu
what if output data is needed in form mentioned below
Current
>

Vehicle: BMW Class
Vehicle: Toyota Class

Required:

BMW
Toyota

If you don't have ">" in your input before vehicle then try

awk -v Tyre='Four' ' $0 ~ /Vehicle:/ { veh=$2 } $0 ~ "Tyre : "Tyre { print veh } ' file

Or

$ awk -v Tyre='Four' ' $0 ~ /Vehicle:/ { sub(">","");veh=$2 } $0 ~ "Tyre : "Tyre { print veh } ' file
BMW
Toyota

Using awk's built-in ability to split records on blank lines, there's no need for a nested loop:

$ awk '$3 ~ /Four/ {print $1}' RS="" FS="\n" datafile

Vehicle: BMW Class
Vehicle: Toyota Class

$

With shell builtins:

FilePath="test_result.txt"
# read line by line
# temporarily add a : to the IFS (whitespace) and split on it
while IFS=":$IFS" read key val junk
do
  case $key in
  ("Vehicle")
    vehicle=$val
  ;;
  ("Tyre")
    if [ "$val" = "Four" ]
    then
      echo "$vehicle"
    fi
  ;;
  esac
done < "$FilePath"