Unixquest945
Unixquest945

Reputation: 123

grep pattern match with line number

I want to get the line number of the matched pattern but I have a condition that the pattern match should have 'digits' . If I use
grep -ri -n "package $i " . | grep -P '\d'
then I would get the line number of the lines matching pattern but also I would get the lines with 'package ' without any digits:

Below output shows me line number 71 for 'package ca-certificates' but there are four more lines for gluterfs that I dont need . I dont need those lines as they dont have any digit in them .

for i in $(awk '{print $1}' ~/Version-pkgs)
do
grep -ri -n   "package $i " . | grep -P '\d'
done

sh search-version-pkgs.sh
./core.pkglist:71:package ca-certificates         2017.2.14   65.0.1.el6_9               arch noarch
./dev.pkglist:1343:package glusterfs-devel \
./dev.pkglist:1346:package glusterfs-api-devel \
./dev.pkglist:1346:package glusterfs-api-devel \
./dev.pkglist:1346:package glusterfs-api-devel \
./dev.pkglist:1343:package glusterfs-devel \
./core.pkglist:234:package initscripts             9.03.58     1.0.3.el6_9.2prerel7.6.0.0.0_88.51.0            arch ${bestArch}
./core.pkglist:397:package nspr                    4.13.1      1.el6
./dev.pkglist:859:package nspr-devel \
./dev.pkglist:859:package nspr-devel \
./core.pkglist:401:package nss                     3.28.4      4.0.1.el6_9       arch ${bestArch}

Running below script gives me exact pattern match i.e. 'package ' but I would not get the line number of them

for i in $(awk '{print $1}' ~/Version-pkgs)
do
egrep -ri    "package $i " . | grep -P '\d'
done

sh search-version-pkgs.sh
./core.pkglist:package ca-certificates         2017.2.14   65.0.1.el6_9               arch noarch
./core.pkglist:package initscripts             9.03.58     1.0.3.el6_9.2prerel7.6.0.0.0_88.51.0            arch ${bestArch}
./core.pkglist:package nspr                    4.13.1      1.el6
./core.pkglist:package nss                     3.28.4      4.0.1.el6_9       arch ${bestArch}
./core.pkglist:package nss-util                3.28.4      1.el6_9          arch ${bestArch}
./core.pkglist:package tzdata                  2018e       3.el6    arch noarch

How can get the output with the line number along with the pattern match as file:lineno.:package pkgname digits

Upvotes: 0

Views: 72

Answers (1)

Corentin Limier
Corentin Limier

Reputation: 5006

for i in $(cut -f1 ~/Version-pkgs)
do
    grep -rin   "package $i.*[0-9]" .
done

no need to use grep twice

Oneliner :

grep -rinf <(sed -E 's,([^ ]*).*,package \1.*[0-9],' ~/Version-pkgs) .

Upvotes: 2

Related Questions