I would like to change:
e·ver·y·bo·dy
to:
e·ver·y·bo·dy
e·ver·y·bo·
e·ver·y·
e·ver·
e·
A for
loop will be greatly preferred.
This also uses a for
loop, albeit an awk for
loop:
$ echo "e·ver·y·bo·dy" | awk -F· -v OFS=· '{print;for (i=NF;i>1;i--){$i="";print;NF--} }'
e·ver·y·bo·dy
e·ver·y·bo·
e·ver·y·
e·ver·
e·
$ echo 'e·ver·y·bo·dy' | awk -F· -v OFS=· '{for (i=1;i<=NF;i++){for (j=1;j<=i;j++)printf "%s%s",$j,j<NF?OFS:"";print""} }'
e·
e·ver·
e·ver·y·
e·ver·y·bo·
e·ver·y·bo·dy
$ echo 'e·ver·y·bo·dy' | awk -F· -v OFS=· '{s="";for (i=1;i<=NF;i++){s=s OFS $i; printf "%s",substr(s,2); print (i==NF)?"":OFS} }'
e·
e·ver·
e·ver·y·
e·ver·y·bo·
e·ver·y·bo·dy
print
command. So the answer is not good.
echo "hi" | awk -F· -v OFS=· '{for (i=NF;i>0;i--){NF=i;print} }'
Mar 20, 2015 at 7:17
You can do it by shorter awk command as below (long to small):
$ awk -F'·' '{while (NF){ print $0;NF--;ORS="·\n"}}' OFS='·' file
e·ver·y·bo·dy
e·ver·y·bo·
e·ver·y·
e·ver·
e·
And from small to long as following:
$ awk -F'·' '{i=1; while(i<NF){ print tmp=tmp$((i++))"·"} print $0}' file
e·
e·ver·
e·ver·y·
e·ver·y·bo·
e·ver·y·bo·dy
If it has to be a for
loop:
IFS=·
for l in $(echo "e·ver·y·bo·dy"); do x="$x$l·"; echo "$x"; done | tac
First we have to set the internal file separator to ·
. Then the for loop runs trough each peace and prints it, but in the wrong order. That's why tac
at the end reverses the order.
Gives me the output:
e·ver·y·bo·dy·
e·ver·y·bo·
e·ver·y·
e·ver·
e·
Here is a python
solution:
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
input_str = 'e·ver·y·bo·dy'
input_list = input_str.split('·')
print input_str
i = len(input_list)
while i > 1:
print '·'.join(input_list[:i-1]) + '·'
i -= 1
Here we first split
the input string using ·
as the delimiter to generate a list and then used list slicing and join
to get the desired output.