【发布时间】:2016-01-20 15:46:45
【问题描述】:
我正在使用sed 重新格式化输入字符串,我想将其中的一部分替换为不同的字符串。
输入字符串是日期,格式为:
%Y-%m-%dT%H:%M:%S.%N%:z
Example:
2016-01-20T08:15:32.398242-05:00
我的目标是将上面示例中的 月份 01 替换为字符串表示形式,例如 Jan。
我已经定义了以下要使用的数组:
declare -A MONTHS=([01]="Jan" [02]="Feb" [03]="Mar" [04]="Apr" [05]="May" [06]="Jun" [07]="Jul" [08]="Aug" [09]="Sep" [10]="Oct" [11]="Nov" [12]="Dec")
我似乎无法让 sed 使用匹配组的值作为 MONTHS 数组的索引。
我尝试过的:
# straightforward sed approach
sed 's/^[0-9]\{4\}-\([0-9]\{2\}\)-.*/${MONTHS[\1]}/g'
# result: ${MONTHS[01]}
# break out of the single quotes
sed 's/^[0-9]\{4\}-\([0-9]\{2\}\)-.*/'"${MONTHS[\1]}"'/g'
# result:
# use double quotes
sed "s/^[0-9]\{4\}-\([0-9]\{2\}\)-.*/${MONTHS[\1]}/g"
# result:
# use double quotes *and* a hardcoded example
sed "s/^[0-9]\{4\}-\([0-9]\{2\}\)-.*/${MONTHS[\1]}, ${MONTHS[01]}/g"
# result: , Jan
是否可以使用来自sed 的匹配组值作为替换中的数组索引?
注意: 我故意避免使用date 函数,因为它的应用可能超出实际日期;但是,我绝对愿意接受 awk 等替代方法。
【问题讨论】:
标签: regex bash replace sed associative-array