0

我将 sed 用于带有 shell 脚本的自动设置程序。我试图在最后一个引号之前添加一个单词,规则是:

  • 由于变量,第一个参数中必须有双引号
  • 最后一个引号之前的单词是未知的
  • 我更喜欢使用 sed 命令的解决方案

文件:

values="word anotherword anyword foo"

剧本:

#!/bin/sh
wordtoadd="bar";
sed -i "s/^values=\(*.\)\"/\1$wordtoadd\"/" filetomodify.txt;

期望的结果:

values="word anotherword anyword foo bar"
4

2 回答 2

1

One way:

sed '/^values=/s/\([^"]*\)"$/\1 '"$wordtoadd"'"/' input

Which, if finds a line starting with values=, replaces the longest match of a series of non-quote characters ([^"]) followed by a quote and the end-of-line ("$) with the match and wordtoend, also putting back the quote (\1 '"$wordtoadd"'").

In your sed expression, \(*.\) should be \(.*\) to quantify the .. And you should also put back the value= part when substituting.

于 2013-07-08T00:46:03.740 回答
0

这可能对您有用(GNU sed):

sed -r 's/(.*)"/\1'"$wordtoadd"'"/' file
于 2013-07-08T05:58:22.287 回答