1

It will eventually be part of a larger script so it needs to be shell scripted. A simple task in other languages, but I'm having trouble accomplishing it in shell. Basically I have a string and I want to insert a "." at all possible indices within the string. The output can be on newlined or separated by spaces. Can anyone help?

Example:
input: "abcd"

output: ".abcd
a.bcd
ab.cd
abc.d
abcd."

OR

output: ".abcd a.bcd ab.cd abc.d abcd."

Mike Weber
  • 179
  • 1
  • 1
  • 10

1 Answers1

2

A simple for loop would do:

input=abcd
for ((i=0; i<${#input}+1; i++))
do
    echo ${input::$i}.${input:$i}
done

This just slices up the string at each index and inserts a .. You can change the echo to something else like appending to an array if you want to store them instead ouf output them, of course.

FatalError
  • 52,695
  • 14
  • 99
  • 116
  • +1, just a (to the OP possibly irrelevant) side note: for this to work under `ksh` as well you need to explicitly specify the starting index, e.g. `${input:0:$i}`. ksh93's parser barks upon `${foo::$bar}`. – Adrian Frühwirth Apr 05 '13 at 18:19
  • That for line doesn't seem to work in sh. So I tried the following but the echo line gives a "bad substitution" error. `max=$((${#input}+1)); for i in 'seq 0 $max'; do; echo ${input::$i}.${input:$i}; done;` *-the ' in the code are actually back ticks ` – Mike Weber Apr 05 '13 at 22:47
  • After further exploration in the system I'm working on it is actually dash. – Mike Weber Apr 06 '13 at 00:50