Bash可以像Python枚举函数一样拆分字符串并对其进行编号



我发现了使用trIFS拆分字符串的有趣方法

https://linuxhandbook.com/bash-split-string/

#!/bin/bash
#
# Script to split a string based on the delimiter
my_string="One;Two;Three"
my_array=($(echo $my_string | tr ";" "n"))
#Print the split string
for i in "${my_array[@]}"
do
echo $i
done

输出

One
Two
Three

基于这段代码,是否可以使用Bash将数字放在字符串前面?

在Python中,有enumerate函数来实现这一点。

number = ['One', 'Two', 'Three']
for i,j in enumerate(number, 1):
print(f'{i} - {j}')

输出

1 - One
2 - Two
3 - Three

我相信应该有类似的技巧可以在Bash Shell中使用awksed来完成,但我现在还想不出解决方案。

我想你可以添加一些类似count=$(($count+1))的东西

#!/bin/bash
#
# Script to split a string based on the delimiter
my_string="One;Two;Three"
my_array=($(echo $my_string | tr ";" "n"))
#Print the split string
count=0
for i in "${my_array[@]}"
do
count=$(($count+1))
echo $count - $i
done

这是@anubhava答案的一个稍微修改过的版本。

y_string="One;Two;Three"
IFS=';' read -ra my_array <<< "$my_string"
# ${!array_name[@]} returns the indices/keys of the array
for i in "${!my_array[@]}"
do
echo "$((i+1)) - ${my_array[i]}"
done

根据bash手册,

可以获得数组的键(索引(以及值${!name[@]}和${!name[*]}扩展到数组变量名称中分配的索引。

我看到你今天早些时候发布了一篇帖子,很抱歉我未能上传代码,但仍然希望这能帮助你

my_string="AA-BBB"
IFS='-' read -ra my_array <<< "$my_string"
len=${#my_array[@]}
for (( i=0; i<$len; i++ )); do
up=$(($i % 2))
#echo $up
if [ $up -eq 0 ]
then 
echo ${my_array[i]} = '"Country name"'
elif [ $up -eq 1 ] 
then
echo ${my_array[i]} = '"City name"'
fi
done

这里有一种标准的bash方法:

my_string="One;Two;Three"
IFS=';' read -ra my_array <<< "$my_string"
# builds my_array='([0]="One" [1]="Two" [2]="Three")'
# loop through array and print index+1 with element
# ${#my_array[@]} is length of the array
for ((i=0; i<${#my_array[@]}; i++)); do
printf '%d: %sn' $((i+1)) "${my_array[i]}"
done
1: One
2: Two
3: Three

最新更新