1

我知道您可以在 bash 中使用 sed 更改文本文件中的一行,显示类似的内容;

name="applicationname" //这不是问题(它会有所不同,这就是我使用 var 的原因)

描述: http: //google.com 或描述:http: //yahoo.com //有时描述中的“价值”会有所不同

描述:http ://mysite.com/depiction.php?package=applicationname //这是我想要实现的格式

通过使用 sed,但我不完全确定如何实现 sed。 http://www.gnu.org/software/sed/

编辑:这就是我刚刚想出的

sed -i "s!Depiction:.*!Depiction: http://mysite.com/depiction.php?package=$name!" ./inputfile

如果在这个特定的文本文件中没有“描述:”怎么办?我如何插入一行:描述:http ://mysite.com/depiction.php?package=applicationname ?

4

5 回答 5

1

我已经设法通过许多试验和错误找到了答案......所以只是为了分享。:)

if grep -Fq "Depiction:" ./file
then
sed -i "s!Depiction:.*!Depiction: http://mysite.com/depiction.php?package=$name" ./file
else
sed -i 1i"Depiction: http://mysite.com/depiction.php?package=$name" ./file
fi
于 2012-04-10T01:44:01.977 回答
1

您可以这样尝试:删除“描述:”的所有实例,然后附加您想要的行

{
  grep -v "Depiction:" filename
  echo "Depiction: ..."
} > newfile && mv newfile filename
于 2012-04-09T17:10:25.650 回答
0

sed 对于简单的替换最有价值。一旦你有了“如果没有找到,就做 X”这样的逻辑,你应该转向更通用的语言。我喜欢Python

from sys import argv, stdout

filename = argv[1]
depiction_found = False
for line in open(filename):
    line.replace('foo', 'bar') #I'm not too sure what you're really trying to do
    if line.startswith("Depiction: "):
        depiction_found = True
    stdout.write(line)

if not depiction_found:
    stdout.write("Depiction: <correct value here>\n")
于 2012-04-09T16:59:06.530 回答
0

This might work for you:

sed -i '/Depiction:.*/{h;s||Depiction: http://mysite.com/depiction.php?package='"$name"'|};$!b;x;/./{x;q};x;a\Depiction: http://mysite.com/depiction.php?package='"$name" ./inputfile

or perhaps as the barebones:

sed -i '/foo/{h;s//FOO/};$!b;x;/./{x;q};x;a\FOO' file

In essence:

  • If foo exists, make a copy in the hold space (HS) and carry out substitution.
  • At end of file ($) check the hold space for evidence or previous substitution and if none append a line.
于 2012-04-09T20:35:48.550 回答
0

如果您不关心订单,请删除它,然后添加。或者使用 awk:

awk 'BEGIN{replacement="Depiction: http://mysite.com/depiction.php?package=applicationname"}/^Depiction:/{print replacement;found=1}!/^Depiction:/{print}END{if(!found)print replacement}' < file

或任何其他高阶语言。

于 2012-04-09T17:01:02.367 回答