在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中。最后,我們輸出提取到的字段值。