Reputation: 201
How would I explode out a number in bash
With this value '12684041234'
Required result '12684041234','1268404123','126840412','12684041','1268404','126840','12684','1268','126','12','1'
Upvotes: 0
Views: 162
Reputation: 2491
with dc :
echo '12684041234' | dc -f - -e '[p10/d0<Z]sZlZx'
explanation :
# -f - is the file to read for the input (/dev/stdin)
# -e '...' is the code to execute
echo '12684041234' | dc -f - -e '
[
p # print the stack
10
/ # divide the stack by 10
d # duplicate the result
0
<Z # while the stack is greater than 0 execute macro Z
] sZ # define macro Z inside [ ]
lZ # load macro Z
x # execute it
'
Upvotes: 1
Reputation: 8711
Using Perl and regex
$ echo '12684041234' | perl -ne ' $x=$_;$i=length($x); while($i>0) { $x=~m/(.{$i})/m; print "$1\n" ; $i-- } '
12684041234
1268404123
126840412
12684041
1268404
126840
12684
1268
126
12
1
Thanks to Nahuel for the below solution
perl -nE '/^.+(?{say$&})(?!)/' <<<12684041234
Upvotes: 1
Reputation: 1809
sed
solution for fun:
$ sed -n ':a;p;s/.$//;/./ba' <<< 12684041234
12684041234
1268404123
126840412
12684041
1268404
126840
12684
1268
126
12
1
Upvotes: 1
Reputation: 2868
The %
can be used to remove prefix of a variable's value.
Give a try to this:
number=12684041234
while [[ "${#number}" -gt 0 ]] ; do
printf ",'%s'" "${number}"
number="${number%?}"
done | cut -b 2-
Output
'12684041234','1268404123','126840412','12684041','1268404','126840','12684','1268','126','12','1'
Upvotes: 2
Reputation: 19
I ain't thinkin' good practices, but to solver this problem. Here's how in Python the solution would be:
from functools import reduce
def f_split_word(s_word):
return s_word
def f_list_explode_word(s_word):
ret = []
s_word_split = list(map(f_split_word, s_word))
for x in range(0, len(s_word_split)):
ret.append(reduce(lambda x,y: str(x) + str(y), s_word_split if x == 0 else s_word_split[:-x]))
return ret
s_word = str('12684041234')
print(f_list_explode_word(s_word))
Upvotes: -1
Reputation: 19315
if n is less than or equals echo $((2**63-1))
for((n=12684041234;n>0;n/=10));do echo $n;done
Upvotes: 2
Reputation: 37424
Using GNU awk:
$ echo 12684041234 | awk 'BEGIN{FS=OFS=""}{for(i=NF;i>=1;i--){print;NF--}}'
12684041234
1268404123
126840412
...
Upvotes: 1
Reputation: 74685
I don't think that there's any built-in way to do what you want, but you can always use a loop:
n=12684041234
for (( i = ${#n}; i > 0; i-- )) do echo ${n:0:i}; done
This just loops from the length of the variable $n
down to 1 and prints substrings of $n
.
Upvotes: 3