-2

I have a requirement to print the first string of a line if last 5 strings match specific input.

Example: Specified input is 2

India;1;2;3;4;5;6
Japan;1;2;2;2;2;2
China;2;2;2;2
England;2;2;2;2;2

Expected Output:

Japan
England

As you can see, China is excluded as it doesn't meet the requirement (last 5 digits have to be matched with the input).

muru
  • 4,723
  • 1
  • 34
  • 78
Sunny1985
  • 91
  • 9
  • What have you tried, and how did it fail? This should be possible within a few minutes of bringing up the Awk manual for the first time. – tripleee Mar 02 '17 at 09:28

4 Answers4

2
grep ';2;2;2;2;2$' file | cut -d';' -f1
  • $ in a regex stands for "end of line", so grep will print all the lines that end in the given string
  • -d';' tells cut to delimit columns by semicolons
  • -f1 outputs the first column
choroba
  • 231,213
  • 25
  • 204
  • 289
0

With sed:

sed -n 's/^\([^;]*\).*;2;2;2;2;2$/\1/p' file

It captures and output non ; first characters in lines ending with ;2;2;2;2;2

It can be shortened with GNU sed to:

sed -nE 's/^([^;]*).*(;2){5}$/\1/p' file
SLePort
  • 15,211
  • 3
  • 34
  • 44
0

You could use awk:

awk -F';' -v v="2" -v count=5 '
   {
     c=0;
     for(i=2;i<=NF;i++){
        if($i == v) c++ 
        if(c>=count){print $1;next}
     }
   }' file

where

  • v is the value to match
  • count is the maximum number of value to print the wanted string
  • the for loop is parsing all fields delimited with a ; in order to find a match

This script doesn't need the 5 values 2 to be consecutive.

oliv
  • 12,690
  • 25
  • 45
0
awk -F\; '/;2;2;2;2;2$/{print $1}' file
Japan
England
Claes Wikner
  • 1,457
  • 1
  • 9
  • 8
  • 1
    Whilst this code snippet is welcome, and may provide some help, it would be [greatly improved if it included an explanation](//meta.stackexchange.com/q/114762) of *how* and *why* this solves the problem. Remember that you are answering the question for readers in the future, not just the person asking now! Please [edit] your answer to add explanation, and give an indication of what limitations and assumptions apply. – Toby Speight Mar 02 '17 at 12:15