Busybox filter string list

0

Consider I have a list like this:

list='item1.service item2.service item3.target item4.service'

I need to filter this list to get something as:

item1 item2 item4

So, there are two things to notice:

  1. I need keep only the .service items.
  2. I need only the "base" names, without the .service suffix.

And one more important information: I am running on busybox, where tools are often crippled (e.g.: my grep has no support for Perl regexes).

I have been struggling against combinations of sed and grep and the best I could get is:

$ echo $list | grep -io '[a-z0-9\-\_@]*.service' | sed 's/\.service//'
item1
item2
item4

but it needs to perform essentially the same match twice for each input, what doesn't look very efficient. Could anyone suggest any better solution, please?

Thanks in advance.

j4x

Posted 2018-12-11T16:06:58.080

Reputation: 137

What does this have to do with Busybox? – JakeGould – 2018-12-11T16:38:20.013

sed does all the job echo "$list"|sed -r 's/[a-z0-9@_-]+\.target//;s/ +/ /g;s/ /\n/g'. This works in BusyBox 1.2.1, very old. – Paulo – 2018-12-11T23:27:47.017

Thanks @Paulo for your response. Unfortunatelly, sed doesn't remove the suffix and the generate output is item1.service instead of simply item1 as I need. – j4x – 2018-12-12T08:03:57.460

1@j4x The sed you posted has the command to cut the suffix, just append it to sed script sed -r 's/[a-z0-9@_-]+\.target//;s/\.service//g;s/ +/ /g;s/ /\n/g'. g flag is needed to replace all matches, without it sed will replace only the first match. – Paulo – 2018-12-12T11:52:08.690

Good. IT is devilish to understand but works! @Paulo, please post an answer so I can mark it. Thanks! – j4x – 2018-12-12T12:13:32.283

Answers

1

list='item1.service item2.service item3.target item4.service'
echo "$list" | sed -r '

# Since the input is only one line, all commands will scan all the pattern space,
# so the commands order matters.

# replace for nothing unwanted text
s/[a-z0-9@_-]+\.target//

# replace for nothing unwanted suffix
# (with 'g' flag the command will replace all occurrences)
s/\.service//g

# squeeze double spaces
s/ +/ /g

# replace space for new line character
s/ /\n/g'

I think this will work in all versions of BusyBox's sed (could be awk too if you have it in your BusyBox).

I just downloaded the latest BusyBox version and ran make menuconfig but couldn't find any reference to Perl regex.

Paulo

Posted 2018-12-11T16:06:58.080

Reputation: 606