我使用sed
重新格式化输入字符串,其中一部分我想用其他字符串替换。使用sed替换关联bash数组中的匹配值
输入字符串是在量的格式的日期:
%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
。
哦,太棒了,这很好用!我非常喜欢它可以让我内嵌替换值,而其他一切都很容易根据我的需要进行修改。谢谢=] – newfurniturey