String 在bash中拆分多个换行符
我需要按照2个或更多换行符的正则表达式模式进行拆分,并将每个匹配组存储为bash中数组的元素。awk和sed没有帮助,因为他们同时在一条线上工作。我的输入字符串包含多行文本。我该怎么做呢?一个解决方案。下面使用的选项卡可以由文件中不包含的另一个字符替换String 在bash中拆分多个换行符,string,bash,split,newline,multiline,String,Bash,Split,Newline,Multiline,我需要按照2个或更多换行符的正则表达式模式进行拆分,并将每个匹配组存储为bash中数组的元素。awk和sed没有帮助,因为他们同时在一条线上工作。我的输入字符串包含多行文本。我该怎么做呢?一个解决方案。下面使用的选项卡可以由文件中不包含的另一个字符替换 str=$(cat newlines.dat) # read file into string str=${str//$'\n'$'\n'/$'\t'} # 2 newlines to 1
str=$(cat newlines.dat) # read file into string
str=${str//$'\n'$'\n'/$'\t'} # 2 newlines to 1 tab
while [[ "$str" =~ $'\t'$'\n' ]] ; do
str=${str//$'\t'$'\n'/$'\t'} # eat up further newlines
done
str=${str//$'\t'$'\t'/$'\t'} # sqeeze tabs
IFS=$'\t' # field separator is now tab
result=( $str ) # slit into array
cnt=0
for x in ${result[@]}; do # print result
((cnt++))
echo -e "--- group $cnt ---\n$x"
done
输入文件:
1111111111
222222222
33333333333
44444444444
5555555555555
66666666666666
77777777
888888888888888
999999
结果是:
--- group 1 ---
1111111111
222222222
--- group 2 ---
33333333333
44444444444
--- group 3 ---
5555555555555
--- group 4 ---
66666666666666
77777777
--- group 5 ---
888888888888888
999999
解决办法。下面使用的选项卡可以由文件中不包含的另一个字符替换
str=$(cat newlines.dat) # read file into string
str=${str//$'\n'$'\n'/$'\t'} # 2 newlines to 1 tab
while [[ "$str" =~ $'\t'$'\n' ]] ; do
str=${str//$'\t'$'\n'/$'\t'} # eat up further newlines
done
str=${str//$'\t'$'\t'/$'\t'} # sqeeze tabs
IFS=$'\t' # field separator is now tab
result=( $str ) # slit into array
cnt=0
for x in ${result[@]}; do # print result
((cnt++))
echo -e "--- group $cnt ---\n$x"
done
输入文件:
1111111111
222222222
33333333333
44444444444
5555555555555
66666666666666
77777777
888888888888888
999999
结果是:
--- group 1 ---
1111111111
222222222
--- group 2 ---
33333333333
44444444444
--- group 3 ---
5555555555555
--- group 4 ---
66666666666666
77777777
--- group 5 ---
888888888888888
999999
为什么需要将元素存储在bash数组中?如果这是您所需要的,那么您当然不能(轻松地)使用awk。如果只需要一次处理一个元素,可以在awk中通过将
RS
设置为空字符串来完成,这会导致“记录分隔符”为一行或多行空行。为什么需要将元素存储在bash数组中?如果这是您所需要的,那么您当然不能(轻松地)使用awk。如果只需要一次处理一个元素,可以在awk中通过将RS
设置为空字符串来完成,这会导致“记录分隔符”为一行或多行空行。