在Shell脚本中拆分字符串以获得不同的组合

时间:2015-12-23 07:53:58

标签: bash

请帮忙。拆分字符串a b c d以提供abcdabbc,{{1}的组合},cdabc使用bash?

字符串可以是任意长度的空格。

3 个答案:

答案 0 :(得分:1)

#!/bin/bash

string='a b c d'
separator=' '
# get number of elements
array=(${string//$separator/$IFS})
elements=${#array[@]}
# remove separators
string="${string//$separator/}"

for ((len = 1; len < $elements; len++))
do
    for ((off = 0; off < $elements - len + 1; off++))
    do
        echo ${string:$off:$len}
    done
done

这应该适用于大多数$separator,而不仅仅是空间。

答案 1 :(得分:1)

#!/bin/bash

input="ab cd   ef gh"                   ## input data

                                        ## v1: consider a b c ... as atoms
s=`sed 's:\s*::g' <<<"$input"`          ## remove all spaces
l=${#s}                                 ## l = length of s
for ((i=0;++i<l;)); do                  ## i = length of substring
  for ((j=-1;++j+i<=l;)); do            ## j = pos of substring
    echo ${s:$j:$i}                     ## print substring
  done
done | sed ':a;N;s/\n/, /;ba'           ## sed to join lines, \n => ,

                                        ## v2: consider ab cd ef ... as atoms
IFS=' ' read -r -a a <<<"$input"        ## put atoms in array
l=${#a[@]}
for ((i=0;++i<l;)); do
  for ((j=-1;++j+i<=l;)); do
    echo ${a[@]:$j:$i}|sed 's:\s*::g'   ## remove spaces when print
  done
done | sed ':a;N;s/\n/, /;ba'

结果:

a, b, c, d, e, f, g, h, ab, bc, cd, de, ef, fg, gh, abc, bcd, cde, def, efg, fgh, abcd, bcde, cdef, defg, efgh, abcde, bcdef, cdefg, defgh, abcdef, bcdefg, cdefgh, abcdefg, bcdefgh
ab, cd, ef, gh, abcd, cdef, efgh, abcdef, cdefgh

答案 2 :(得分:1)

  $ st="a b c d"
  $ eval echo $(echo "${st}" | sed -e 's/[^ ]\+/{&,}/g' -e 's/ //g')
  abcd abc abd ab acd ac ad a bcd bc bd b cd c d

使用嵌套大括号扩展{ ,}来扩展和组合字符串中的字母。 sed用于获取字符串并将输入转换为formar {a,}{b,}{c,}{d,}。然后使用eval来评估后面的整个命令,就像您尝试使用cmdline一样。

我不确定逗号,是否是输出的要求,但可以通过将其汇总到tr来轻松实现。像这样的东西

$ eval echo $(echo "${st}" | sed -e 's/[^ ]\+/{&,}/g' -e 's/ //g') | tr ' ' ','
abcd,abc,abd,ab,acd,ac,ad,a,bcd,bc,bd,b,cd,c,d

这也适用于由空格分隔的字符串内的单词。

$ st='lorem ipsum dolor'
$ eval echo $(echo "${st}" | sed -e 's/[^ ]\+/{&,}/g' -e 's/ //g') | tr ' ' ','  
loremipsumdolor,loremipsum,loremdolor,lorem,ipsumdolor,ipsum,dolor