v21*_*217 3 bash shell ubuntu gnu-coreutils
为什么不能使用以下bash代码?
for i in $( echo "emmbbmmaaddsb" | split -t "mm" )
do
echo "$i"
done
Run Code Online (Sandbox Code Playgroud)
预期产量:
e
bb
aaddsb
Run Code Online (Sandbox Code Playgroud)
由于您需要换行符,因此您只需使用换行符替换mm字符串中的所有实例即可.在纯粹的原生bash中:
in='emmbbmmaaddsb'
sep='mm'
printf '%s\n' "${in//$sep/$'\n'}"
Run Code Online (Sandbox Code Playgroud)
如果你想在更长的输入流上做这样的替换,你可能最好使用awk,因为bash的内置字符串操作不能很好地扩展到超过几千字节的内容.BashFAQ#21中给出的gsub_literalshell函数(后端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;
}
'
}
Run Code Online (Sandbox Code Playgroud)
......在这种情况下,用作:
gsub_literal "mm" $'\n' <your-input-file.txt >your-output-file.txt
Run Code Online (Sandbox Code Playgroud)
使用awk,您可以使用gsub替换所有正则表达式匹配项。
与您的问题一样,要将两个或多个 'm' 字符的所有子字符串替换为新行,请运行:
echo "emmbbmmaaddsb" | awk '{ gsub(/mm+/, "\n" ); print; }'
Run Code Online (Sandbox Code Playgroud)
电子
bb
aaddsb
gsub() 中的“g”代表“全局”,意思是到处替换。
您还可以要求只打印 N 个匹配项,例如:
echo "emmbbmmaaddsb" | awk '{ gsub(/mm+/, " " ); print $2; }'
Run Code Online (Sandbox Code Playgroud)
bb
下面给出了一个更通用的示例,其中没有用单个字符定界符替换多字符定界符:
使用参数扩展:(来自@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
Run Code Online (Sandbox Code Playgroud)
一种更粗略的方式
#!/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
Run Code Online (Sandbox Code Playgroud)
推荐的用于字符替换的工具是用于一次正则表达式或全局正则表达式sed的命令,您甚至不需要循环或变量。s/regexp/replacement/s/regexp/replacement/g
用管道echo传输您的输出,并尝试用mm换行符替换字符\n:
echo "emmbbmmaaddsb" | sed 's/mm/\n/g'
输出为:
e
bb
aaddsb
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15939 次 |
| 最近记录: |