Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
954 views
in Technique[技术] by (71.8m points)

print all prefixes of a string - translate from python to bash

I have a shell script that needs to take an .so and get all its prefixes, where a prefix is the part of the name, up until the ".so" part + the next part up until the ".".

Example: for 'example.so.1' we'll have the following prefixes: 'example.so', 'example.so.1'

I have a python(3) code that does it, and I want to get a bash equivalent.


Bash wrapper for the Python source:

#!/bin/bash


dst='/tmp'
for src in 'example.so' 'example.so.1' 'example.so.1.2' 'example.so.1.2.3'; do
python3 -c "
import os, sys, itertools as it, re;
so_path = os.path.abspath(sys.argv[1]);
dst = sys.argv[2];
so = os.path.basename(so_path);
so_name = so.split('.')[0];
regex = '.w+';
for suffix in it.accumulate(re.findall(regex, so)):
    dst_so = os.path.join(dst, so_name + suffix)
    print('src: {}. dst: {}'.format(so_path, dst_so))
" "${src}" "${dst}";
done

This is my tryout in bash using awk (it's not complete and only prints the source. I keep tweaking it, but can't get it do exactly what I want):

#!/bin/bash

dst='/tmp'
delimiter='.'
for src in 'example.so' 'example.so.1' 'example.so.1.2' 'example.so.1.2.3'; do
    for nubmer_of_delimiters in `seq $(echo ${src} | grep ${delimiter} | wc -l)`; do
        echo ${src} :: ${src} | awk -F. '{print $nubmer_of_delimiters}';
    done
done

What would be the best way to achieve this? (I'm guessing awk, though I did try to use a bit og cut, sed, etc.

The bash code must run on clean ubuntu18 with no extra installs

question from:https://stackoverflow.com/questions/65880791/print-all-prefixes-of-a-string-translate-from-python-to-bash

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Looks like you should be able to just shave in a loop.
given f=example.so.1.2.3, try

$: while [[ "$f" =~ [.]so[.] ]]; do echo "$f"; f=${f%.*}; done; echo "$f"
example.so.1.2.3
example.so.1.2
example.so.1
example.so

If you want the smaller ones first, pass it through a sort.

$: { while [[ "$f" =~ [.]so[.] ]]
>    do echo "$f"
>       f=${f%.*}
>    done
>    echo "$f"
>  } | sort
example.so
example.so.1
example.so.1.2
example.so.1.2.3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...