Remove all matches containing a string until its next space

I want to delete all matches in a text following this pattern:

  • Each match starts with linux-
  • Each match ends with a space
  • (Remove linux-* until immediate next space)

EXAMPLE:
From this text:

ibudev1 libudev1 libweather-ion7 libxatracker2 linux-generic linux-headers-generic linux-image-generic linux-libc-dev linux-signed-generic mesa-va-drivers mesa-va-drivers mesa-vdpau-drivers mesa-vdpau-drivers milou

Get this:

ibudev1 libudev1 libweather-ion7 libxatracker2 mesa-va-drivers mesa-va-drivers mesa-vdpau-drivers mesa-vdpau-drivers milou

It is meant to be run on Ubuntu, so use bash, sed, awk, etc... the linux versions and if possible posix for any system (cygwin, etc) better.

something along these lines:

 sed 's/[ ][ ]*linux-[^ ][^ ]*//g' myFile
1 Like

The previous sample matches and removes leading space.
It's also possible with trailing space. With portable perl one can even include TABs

perl -pe 's/linux-\S+\s+//g'

Most exact is a "begin anchor" and trailing space becomes optional

perl -pe 's/(^|\s)linux-\S+\s*//g'

A recent GNU-Linux like Ubuntu can use sed -r instead of the perl -pe .
Just seeing the latter sample does not work because the trailing \s* consumes the leading space for a subsequent match.
Because I have no good idea for a fix, here is again one with leading spaces (and also allowing the beginning of the line):

perl -pe 's/(^|\s)linux-\S+//g'
1 Like

Are you aware that these stipulations will exclude a "linux-something" at the lines end from being removed because there will be no space afterwards? Maybe this is not what you want. Also notice that your clause 2 means that the space immediately following the word "linux-*" will be removed too.

If your goal is indeed to remove the last match too i'd suggest:

sed 's/linux-[^ ]* \{0,1\}//g' /path/to/file

If you want to retain the blank following the word but would not want to add a space at the end of the string then this:

sed 's/linux-[^ ]*\( \{0,1\}\)/\1/g' /path/to/file

I hope this helps.

bakunin

1 Like

Any of the two work, because the apt command uses space as argument separator, when there are one or more spaces at the end they are ignored and two or more spaces in any place are condensed into one.