将捕获的组作为数组索引发送到sed

时间:2017-09-16 01:23:51

标签: linux bash unix sed

file=/home/root/customers_and_contacts.txt
month[1]="January"
month[2]="Febuary"
month[3]="March"
month[4]="April"
month[5]="May"
month[6]="June"
month[7]="July"
month[8]="August"
month[9]="September"
month[10]="October"
month[11]="November"
month[12]="December"

cat $file | sed "s/\b[0-9]\([0-9]\)-\?\([0-9]\{2\}\)-\?\([0-9]\{4\}\)\b/$(month[\1])"

为简单起见,我创建了上述文档。基本上customers_and_contacts.txt包含我想将月份转换为月份实际名称的日期。

Month[0]似乎有用

\1似乎有用

当你把它们放在一起时,它不会

编辑----

假设输入文件包含n行,如下所示:

  08-06-1998

  02-03-2014

输出文件应如下所示

   August 06-1998

   February 03-2014

1 个答案:

答案 0 :(得分:0)

首先,你有一个错误:要访问bash数组的元素,你可以使用大括号:

${month[1]}

否则会抱怨month[1] command not found或其他什么。

其次,bash会在将命令发送到子shell之前先扩展所有变量,所以假设你修复了上面的bug,你将发送以下命令(${month[\1]}扩展到January,因为\ 1在bash中只是1:

cat /home/root/customers_and_contacts.txt | \
  sed "s/\b[0-9]\([0-9]\)-\?\([0-9]\{2\}\)-\?\([0-9]\{4\}\)\b/January"

最后,原始设计不会按照您的意图进行,因为除了单一模式替换之外,它需要多个替换逻辑。

您可以使用多个-e选项在sed中执行多个替换逻辑:

cat $file | \
  sed -e "s/..1../..${month[1]}../" \
      -e "s/..2../..${month[2]}../" \
      -e "s/..3../..${month[3]}../" \
      -e..

您可以使用原始代码填写空白(..)。