Sed在分隔符之前移动文本

时间:2013-03-22 17:51:14

标签: regex sed awk

我有一个csv文件,如下所示:

"foo","bar","lorem","ipsum"
"foo"."bar","XX lorem","ipsum"

我需要在以“xx”结尾的字段中转换以“xx”开头的字段:

"foo","bar","lorem","ipsum"
"foo"."bar","lorem xx","ipsum"

sed(或awk)可以帮帮我吗? (“xx”是一个字符串而不是正则表达式结果)

2 个答案:

答案 0 :(得分:4)

sed -r 's/XX ([^"]+)/\1 XX/' filename

答案 1 :(得分:4)

sed -r 's/"(XX) ([^"]*)"/"\2 \1"/g'

试验:

kent$  echo '"foo","bar","lorem","ipsum XX"
"foo"."XX bar","XX lorem","ips XX um"'|sed -r 's/"(XX) ([^"]*)"/"\2 \1"/g'
"foo","bar","lorem","ipsum XX"
"foo"."bar XX","lorem XX","ips XX um"

注意

  • 这将在所有字段上执行此逻辑,以XX开头。
  • 字段中的XX,但不在起点,将被忽略(参见上面的示例)
  • !!!如果XX具有在正则表达式中具有特殊含义的字符,则该命令可能会失败。例如,如果XX是.*