如何在bash中的多字符分隔符上拆分字符串?

时间:2016-11-18 22:28:54

标签: bash shell ubuntu gnu-coreutils

为什么不使用以下bash代码?

for i in $( echo "emmbbmmaaddsb" | split -t "mm"  )
do
    echo "$i"
done

预期产出:

e
bb
aaddsb

4 个答案:

答案 0 :(得分:7)

由于您需要换行符,因此您只需使用换行符替换字符串中mm的所有实例即可。纯粹的原生bash:

in='emmbbmmaaddsb'
sep='mm'
printf '%s\n' "${in//$sep/$'\n'}"

如果你想在更长的输入流上做这样的替换,你可能最好使用awk,因为bash的内置字符串操作不能很好地扩展到超过几千字节的内容。 BashFAQ #21中提供的gsub_literal shell函数(后跟awk)适用:

# Taken from http://mywiki.wooledge.org/BashFAQ/021

# usage: gsub_literal STR REP
# replaces all instances of STR with REP. reads from stdin and writes to stdout.
gsub_literal() {
  # STR cannot be empty
  [[ $1 ]] || return

  # string manip needed to escape '\'s, so awk doesn't expand '\n' and such
  awk -v str="${1//\\/\\\\}" -v rep="${2//\\/\\\\}" '
    # get the length of the search string
    BEGIN {
      len = length(str);
    }

    {
      # empty the output string
      out = "";

      # continue looping while the search string is in the line
      while (i = index($0, str)) {
        # append everything up to the search string, and the replacement string
        out = out substr($0, 1, i-1) rep;

        # remove everything up to and including the first instance of the
        # search string from the line
        $0 = substr($0, i + len);
      }

      # append whatever is left
      out = out $0;

      print out;
    }
  '
}

...在这种情况下,用作:

gsub_literal "mm" $'\n' <your-input-file.txt >your-output-file.txt

答案 1 :(得分:4)

下面给出了一个更一般的例子,没有用单个字符分隔符替换多字符分隔符:

使用参数扩展:(来自@gniourf_gniourf的评论)

#!/bin/bash

str="LearnABCtoABCSplitABCaABCString"
delimiter=ABC
s=$str$delimiter
array=();
while [[ $s ]]; do
    array+=( "${s%%"$delimiter"*}" );
    s=${s#*"$delimiter"};
done;
declare -p array

更粗暴的方式

#!/bin/bash

# main string
str="LearnABCtoABCSplitABCaABCString"

# delimiter string
delimiter="ABC"

#length of main string
strLen=${#str}
#length of delimiter string
dLen=${#delimiter}

#iterator for length of string
i=0
#length tracker for ongoing substring
wordLen=0
#starting position for ongoing substring
strP=0

array=()
while [ $i -lt $strLen ]; do
    if [ $delimiter == ${str:$i:$dLen} ]; then
        array+=(${str:strP:$wordLen})
        strP=$(( i + dLen ))
        wordLen=0
        i=$(( i + dLen ))
    fi
    i=$(( i + 1 ))
    wordLen=$(( wordLen + 1 ))
done
array+=(${str:strP:$wordLen})

declare -p array

参考 - Bash Tutorial - Bash Split String

答案 2 :(得分:3)

对于一个正则表达式或全局sed,推荐的字符替换工具是s/regexp/replacement/命令s/regexp/replacement/g,您甚至不需要循环或变量。

管道您的echo输出并尝试使用换行符mm替换字符\n

echo "emmbbmmaaddsb" | sed 's/mm/\n/g'

输出结果为:

e
bb
aaddsb

答案 3 :(得分:2)

使用 awk ,您可以使用 gsub 替换所有正则表达式匹配项。

与您的问题相同,要将两个或多个'm'字符的所有子字符串替换为新行,请运行:

echo "emmbbmmaaddsb" | awk '{ gsub(/mm+/, "\n" ); print; }'
  

e

     

bb

     

aaddsb

gsub()中的“ g”代表“全局”,这意味着到处替换。

您可能还要求仅打印N个匹配项,例如:

echo "emmbbmmaaddsb" | awk '{ gsub(/mm+/, " " ); print $2; }'
  

bb