-1

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
  • This is really not that hard. What have you tried? – Tigger May 15 '17 at 12:01
  • I tried this command after putting source file "out" and required numbers in file list "for i in cat list;do if [[ grep -w $i out ]];then grep -w $i out;else echo $i" :not found";fi ;done", but i got no headers. – Fady.Fouad May 15 '17 at 12:03
0

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
2

You can try something like this:

awk '{if(match($0,":")) header=$0; if($0 == 2516) printf("%s\n%s\n",header,$0)}' input_file.txt

Where "2516" is the number you are searching for.

obs: I'm assuming that all the labels ends with ":".

  • Can i put the numbers i am searching for in a file (not only 2516)?? – Fady.Fouad May 15 '17 at 12:27
0

awk approach:

awk -v RS="#####" -v num=2515 '$0~/[0-9a-zA-Z_]+:/{ 
     getline nl; if (nl~num){sub("\n", "", $0); printf("%s%d\n",$0,num)}}' file

The output:

IGHTY_BBBT:
2515

RS="#####" - treating ##### as record separator

-v num=2515 - a variable containing search number

$0~/[0-9a-zA-Z_]+:/ - capturing header line

getline nl - get next record containing numbers

if (nl~num) - if search number is matched within a line of numbers

  • Can i put the numbers i am searching for in a file (not only 2515) ?? – Fady.Fouad May 15 '17 at 12:32
  • @Fady.Fouad, do you want to search by multiple numbers? – RomanPerekhrest May 15 '17 at 12:34
  • Yes by multiple numbers in a file – Fady.Fouad May 15 '17 at 13:30
  • @Fady.Fouad, and how they will be separated, by space or by newline within a file? – RomanPerekhrest May 15 '17 at 13:32
  • By new line within file. – Fady.Fouad May 15 '17 at 14:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.