Last active
May 12, 2019 09:55
-
-
Save MasterEx/d7e09b5e163d0ebcaf9b7edabbb82286 to your computer and use it in GitHub Desktop.
Print all the substrings of a string in Bash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ ./substrings.bash '1234567890' 133 | |
1234567890 | |
$ ./substrings.bash '1234567890' 10 | |
1234567890 | |
$ ./substrings.bash '1234567890' 9 | |
1234567890 | |
123456789 | |
234567890 | |
$ ./substrings.bash '1234567890' 8 | |
1234567890 | |
123456789 | |
234567890 | |
12345678 | |
23456789 | |
34567890 | |
$ ./substrings.bash '1234567890' 7 | |
1234567890 | |
123456789 | |
234567890 | |
12345678 | |
23456789 | |
34567890 | |
1234567 | |
2345678 | |
3456789 | |
4567890 | |
$ ./substrings.bash '1234567890' 1 | |
1234567890 | |
123456789 | |
234567890 | |
12345678 | |
23456789 | |
34567890 | |
1234567 | |
2345678 | |
3456789 | |
4567890 | |
123456 | |
234567 | |
345678 | |
456789 | |
567890 | |
12345 | |
23456 | |
34567 | |
45678 | |
56789 | |
67890 | |
1234 | |
2345 | |
3456 | |
4567 | |
5678 | |
6789 | |
7890 | |
123 | |
234 | |
345 | |
456 | |
567 | |
678 | |
789 | |
890 | |
12 | |
23 | |
34 | |
45 | |
56 | |
67 | |
78 | |
89 | |
90 | |
1 | |
2 | |
3 | |
4 | |
5 | |
6 | |
7 | |
8 | |
9 | |
0 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# Periklis Ntanasis <[email protected]> - 2019 | |
# Prints all the substrings of the given string ("word") up to a minimum length ("min_length"). | |
function getSubstrings { | |
local word=$1 | |
local length=${#1} | |
local min_length=$2 | |
local remove=0 | |
local retval=() | |
if [[ $min_length -gt $length ]]; then | |
min_length=$length | |
fi | |
while [ $remove -lt $length ]; do | |
start=0 | |
len=$(($length-$remove)) | |
if [[ len -lt min_length ]]; then | |
exit | |
fi | |
while [ $(($start+$len)) -le $length ]; do | |
substring=${word:$start:$len} | |
echo $substring | |
start=$(($start+1)) | |
done | |
remove=$(($remove+1)) | |
done | |
} | |
getSubstrings $1 $2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment