两个令牌之间的全球转型

时间:2012-09-24 09:02:56

标签: regex sed

我的问题似乎很简单,但我发现很难转换成sed表达式。

我需要在文件中的某些标记之间“低估”名称。因此,如果该行包含令牌:=,我需要在这两个令牌之间将“多字名称”转换为“multi_word_name”。

我知道在令牌之间进行两步匹配然后用下划线全局替换空格是相当容易的但是我找不到保留不匹配部分行以便写回文件的方法。

2 个答案:

答案 0 :(得分:3)

这可能对你有用(GNU sed,tr和bash):

sed 's/:[^=]*=/$(tr " " "_" <<<"&")/g;s/.*/echo "&"/e' file

或仅使用sed:

sed ':a;/:[^_=]*=/!b;s//\n&\n/;h;s/.*\n\(.*\)\n.*/\1/;y/ /_/;H;g;s/\n.*\n\(.*\)\n\(.*\)/\2\1/;ta' file

答案 1 :(得分:2)

您可以通过sed的两次调用来完成此操作:

echo 'pre with space :multi word name=post with space' \
| sed 's/[:=]/\n&/g' | sed '/^:/s/ /_/g' | tr -d '\n'

要对文件进行此操作,您可以执行以下操作(在bash中):

while read; do 
  echo "$REPLY" | sed 's/[:=]/\n&/g' | sed '/^:/s/ /_/g' | tr -d '\n'
  echo
done < infile

虽然awk将是更适合该任务的工具:

awk -F '[:=]' '{ gsub(" ", "_", $2); print $1 ":" $2 "=" $3 }' infile