menteith
menteith

Reputation: 678

Search for a (regex) match and then reformatting output in Linux

My aim is to search for packages that start with (or consist of) a given string since this is not possible with the command pacman from Arch Linux. The easiest approach for finding packages is to execute pacman -Sl |grep vivaldi, where vivaldi is a package name, which will give:

herecura vivaldi 2.3.1440.60-1 [installed]
herecura vivaldi-ffmpeg-codecs 71.0.3578.98-1 [installed]
herecura vivaldi-snapshot 2.4.1468.4-1

Easy as it is, it has a flow: it searches for a given package name everywhere but the package name is always between first and second space. Quite simple workaround is to the the following

pacman -Sl | grep -P "(?:[a-z0-9-]+) vivaldi"

The console will show output similar to the one below:

herecura vivaldi 2.3.1440.60-1 [installed]
herecura vivaldi-ffmpeg-codecs 71.0.3578.98-1 [installed]
herecura vivaldi-snapshot 2.4.1468.4-1

It will give (perhaps) the correct result which is the same as the one above. But there is another caveat: I'd like to to rearrange the output to to the form:

vivaldi 2.3.1440.60-1 [herecura] [installed] 
vivaldi-ffmpeg-codecs 71.0.3578.98-1 [herecura] [installed]
vivaldi-snapshot 2.4.1468.4-1 [herecura]

I'm quite close to it by executing the command:

pacman -Sl | grep -P "(?:[a-z0-9-]+) vivaldi" | awk '{print $2, $3, $4, $1}'

vivaldi 2.3.1440.60-1 [installed] herecura
vivaldi-ffmpeg-codecs 71.0.3578.98-1 [installed] herecura
vivaldi-snapshot 2.4.1468.4-1  herecura
vivaldi-snapshot-ffmpeg-codecs 72.0.3626.97-1  herecura

However, this is not a good approach as it uses grep with awk but awk solely will suffice because it also supports regexes (e.g. see this blog post).

This is all I get. Unfortunately, I cannot combine all I've written into one command (I'm planning to write an alias or a function).

Upvotes: 2

Views: 354

Answers (1)

RavinderSingh13
RavinderSingh13

Reputation: 133650

Could you please try following(if I got it correctly), since you mentioned string will be in between 1st and 2nd space only so that becomes the 2nd field of line then. Now if we want to check for 2nd field's value I have put condition for 2nd field to check if current line's 2nd field is vivaldi then do printing.

pacman -Sl | awk '$2~/vivaldi/{print $2, $3, $4, $1}'

As per OP's comment aneed to wrap $1 in [ and ] so adding following now.

pacman -Sl | awk '$2~/vivaldi/{print $2, $3, $4, "[" $1 "]"}'

Upvotes: 1

Related Questions