search a string and print the string and it’s header Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of search a string and print the string and it’s header without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I need to search for a string (number here), and print it’s header or title using grep or awk or anything.

please check this example:

Input file content:

#####
Production_Broad:
#####
678
544
#####
IGHTY_BBBT:
#####
1666
2515
2516
2517
2518
#####
Jaguar:
#####
280
#####
Loyalty:
#####
5179
#####
MC_Addr:
#####
544
577890
#####
erce_Ban_1:
#####
7455
5656

I want to search for the number “2515”, and it gives me below output:

IGHTY_BBBT:
2515

and if i searched for “5179”, the output should be as below:

Loyalty:
5179

Answer

If headers are identified by those ##### lines, and the list of IDs to search for is in a ids.txt file (one per line), you could do:

awk '
  !ids_processed{ids[$0]; next}
  $0 == "#####" {getline header; getline; next}
  $0 in ids     {print header ORS $0}' ids.txt ids_processed=1 input.txt

For instance, if ids.txt contains

2515
544
577890

On your sample, that would give:

Production_Broad:
544
IGHTY_BBBT:
2515
MC_Addr:
544
MC_Addr:
577890
We are here to answer your question about search a string and print the string and it’s header - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji