我有一个变量 $b,我想将其分成两个变量 $startt 和 $finisht。
#!/bin/bash
b='08:10:00','11:12:00'
b=$(echo "$b" | tr -d "'")
IFS=',' read -r _ startt finisht _ <<<"$b"
echo "$startt"
echo "$finisht"
以下是所需的输出。startt = 08:10:00 和 finisht = 11:12:00。但是当我运行此脚本时,我只得到 11:12:00。我想尽可能高效地拆分变量。有人能帮忙吗?
答案1
使用shell 参数扩展:
startt=${b%,*} # cut off the comma and everything that follows
finisht=${b#*,} # cut off the comma and everything that precedes
>>>b='08:10:00','11:12:00'
>>>echo $b
08:10:00,11:12:00
>>>startt=${b%,*}
>>>finisht=${b#*,}
>>>echo $startt
08:10:00
>>>echo $finisht
11:12:00