簡體   English   中英

在Shell腳本中拆分字符串以獲取不同的組合

[英]Split String in Shell Script to get different combinations

請幫忙。 使用bash拆分字符串abcd以提供abcdabbccdabcbcd

字符串可以是任意長度,帶有空格。

#!/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有用,而不僅僅是空間。

#!/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
  $ 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用於獲取字符串並將輸入轉換為形式{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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM