Vishwanath Dalvi
Vishwanath Dalvi

Reputation: 36671

Filter a file using shell script tools

I have a file which contents are

E006:Jane:HR:9800:Asst
E005:Bob:HR:5600:Exe
E002:Barney:Purc:2300:PSE
E009:Miffy:Purc:3600:Mngr
E001:Franny:Accts:7670:Mngr
E003:Ostwald:Mrktg:4800:Trainee
E004:Pearl:Accts:1800:SSE
E009:Lala:Mrktg:6566:SE
E018:Popoye:Sales:6400:QAE
E007:Olan:Sales:5800:Asst

I want to fetch List all employees whose emp codes are between E001 and E018 using command including pipes is it possible to get ?

Upvotes: 1

Views: 200

Answers (4)

glenn jackman
glenn jackman

Reputation: 247142

Just do string comparison: Since all your sample data matches, I changed the boundaries for illustration

awk -F: '"E004" <= $1 && $1 <= "E009" {print}'

output

E006:Jane:HR:9800:Asst
E005:Bob:HR:5600:Exe
E009:Miffy:Purc:3600:Mngr
E004:Pearl:Accts:1800:SSE
E009:Lala:Mrktg:6566:SE
E007:Olan:Sales:5800:Asst

You can pass the strings as variables if you don't want to hard-code them in the awk script

awk -F: -v start=E004 -v stop=E009 'start <= $1 && $1 <= stop {print}'

Upvotes: 0

hochl
hochl

Reputation: 12960

You can use awk for such cases:

$ gawk 'BEGIN { FS=":" } /^E([0-9]+)/ { n=substr($1, 2)+0; if (n >= 6 && n <= 18) { print } }' < data.txt
E006:Jane:HR:9800:Asst
E009:Miffy:Purc:3600:Mngr
E009:Lala:Mrktg:6566:SE
E018:Popoye:Sales:6400:QAE
E007:Olan:Sales:5800:Asst

Is that the result you want? This example intentionally only prints employees between 6 and 18 to show that it filters out records. You may print some fields only using $1 or $2 as in print $1 " " $2.

Upvotes: 1

Emil Sit
Emil Sit

Reputation: 23562

Use sed:

sed -n -e '/^E001:/,/^E018:/p' data.txt

That is, print the lines that are literally between those lines that start with E001 and E018.

If you want to get the employees that are numerically between those, one way to do that would be to do comparisons inline using something like awk (as suggested by hochl). Or, you could take this approach preceded by a sort (if the lines are not already sorted).

sort data.txt | sed -n -e '/^E001:/,/^E018:/p'

Upvotes: 1

Vsevolod Dyomkin
Vsevolod Dyomkin

Reputation: 9451

You can try something like this: cut -b2- | awk '{ if ($1 < 18) print "E" $0 }'

Upvotes: 0

Related Questions