With perl:
<your-file expand | perl -lpe '
($indent, $txt) = /^( *)(.*)/;
$depth = length($indent) / 2;
$part[$depth] = $txt;
$_ = join ".", @part[0..$depth]'
Or golfed:
<your-file expand|perl -lpe'
my$d;/^( (?{$d++}))*/;$p[$d]=$'\'';$_=join".",@p[0..$d]'
(also allowing the text to start with one space character if there's an evenodd number of spaces at the start of the line).
expand expands TABs if any into spaces, assuming tab stops every 8 columns, but that can be changed with options.
An awk equivalent could be:
<your-file expand | awk '
BEGIN {
OFS = "."
while ((getline line) > 0) {
match(line, /^ */)
$ (NF = RLENGTH / 2 + 1) = substr(line, RLENGTH + 1)
print
}
}'
Note that they give:
foo
foobar
foobar.bar
foobar.baz
foobar.baz.bat
bar
I'm assuming the missing foobar line in your expected output is an oversight.