在Linux中,cut
命令本身不支持嵌套
#!/bin/bash input="one,two,three" IFS=',' read -ra ADDR <<< "$input" nested_cut() { local input="$1" local delimiter="$2" local field_index="$3" IFS="$delimiter" read -ra fields <<< "$input" echo "${fields[$field_index]}" } first_field=$(nested_cut "$input" ',' 0) echo "First field: $first_field"
在这个示例中,我们定义了一个名为nested_cut
的函数,它接受三个参数:输入字符串、分隔符和要提取的字段索引。然后,我们使用IFS
(内部字段分隔符)将输入字符串分割成字段,并输出指定索引的字段。
在脚本中,我们将输入字符串one,two,three
存储在变量input
中,并使用IFS=',' read -ra ADDR <<< "$input"
将其分割成数组ADDR
。接下来,我们调用nested_cut
函数来提取第一个字段,并将其值存储在变量first_field
中。最后,我们输出提取到的字段值。