using a another delimiter with sed?

Hi there,

After lots of reading I figured out how to use sed to parse my file.
This file is called services.txt:

00a1:ffff0000:0018:01f4:1:477   
BravaNL                         
00a2:ffff0000:0018:01f4:1:471   
MAX                             
00a3:ffff0000:000b:01f4:1:390   
HaberT�rk
00a6:ffff0000:0019:01f4:25:203  
Veronica/Disney XD

I have a text-file with on each line a service-name in it, called names.txt:

Max
BravaNL
Veronica/Disney XD

I want to use a bash script that uses a while loop to read each line from names.txt and then print out the serivice-id from the services.txt file.
The service-id is the line -before- the name in services.txt.
so for example:
The service-id of "BravaNL" would be 00a1:ffff0000:0018:01f4:1:477

After lots of searching on this board, I almost got it right using this script:

while read line
do
    result=`sed -n -e "/^$line$/{x;p;q;};h" services.txt`
    if [ "$result" = "" ]
    then
        echo "Not found"
        echo ""
    else
        echo "$result"
     fi
done <names.txt

I have the following: sed -n -e "/^$line$/{x;p;q;};h"
Where $line would be the service-name from names.txt.

The following rules apply:
Sed must print the line before the search-result: done
Sed must only find complete matches for the service-names: done
If sed find multiple matches it should only process the first: done
Sed should be able to handle service-names with a slash "/" in it: FAIL

It works for all names except for the ones with a / in them:

00a6:ffff0000:0019:01f4:25:203  
Veronica/Disney XD

I cannot put a break "\" in the $line.
So I would like to use another delimiter and make sed ignore the slashes.
Is this possible?

Yes it's possible. I often use use equal signs because path names contain slashes.
See: Using sed with variables

result=`sed -n -e "!^$line$!{x;p;q;};h" services.txt`

regards,
Ahamed

Well I tried to use another delimiter but it seems to be unsupported.
The / works:

sed -n -e "/^Nederland 1$/{x;p;q;};h" services 
1f44:ffff0000:0008:01f4:1:331

However using ! will not:

sed -n -e "!^Nederland 1$!{x;p;q;};h" services
sed: Unsupported command ^

The sed program comes with busybox, maybe it differs from gnu-sed in a way that it doesn't support other delimiters?

That's not how alternative delimiters work for addresses. You must precede the opening delimiter with a backslash.

sed -n '\!reg_ex_here!p'

As opposed to its usage in a substitution command which does not use the preceding backslash at the beginning:

sed -n 's!reg_ex_here!&!p'

Also, you may want to keep in mind that the exclamation point introduces history expansion in some shells, even when in double quotes.

Regards,
Alister

1 Like

Thanks a million!
Well since many service names contain a ! % or @ the best delimiter would be =.

sed -n -e "\=^Veronica/Disney XD$={x;p;q;};h" services
00a6:ffff0000:0019:01f4:25:203