【问题标题】:Inserting variable after pattern using sed使用 sed 在模式后插入变量
【发布时间】:2013-08-22 07:57:30
【问题描述】:

您好,我尝试在 Bash 脚本中使用 Sed,但遇到了问题。 (我对他们俩都是新手)

我正在尝试在标志 <!-- Beginning git log --> 之后插入 $log

#!/bin/bash
log=`git log -1 --stat --date=short --pretty=format:'[ %cd | %an | %s ]'`
sed "/<!-- Beginning git log -->/a $log" ~/opt/prime.dropbox/commit.md

所以在 commit.md 中我会:

some text
<!-- Beginning git log -->
git log output
some text

我已经尝试了所有可能的单引号/双引号技巧,.. 或者可能只是所有错误的技巧。

这是我最常遇到的错误。

sed: -e expression #1, char 102: unknown command: `f'

我知道 awk 应该有一个更简单的方法,但我已经很接近了。 ^^

也许是 Html 字符 &lt;!-- --&gt; 阻塞或什么?

谢谢

【问题讨论】:

  • 可能git log 的输出包含sed 特有的字符。 $log 的值是多少?
  • [ 2013-08-20 |塞尔吉奥 |没有 -p 的 git 日志] index.html | 2 +- 1 个文件已更改,1 个插入 (+),1 个删除 (-) 是的,看起来像。但我不想让 sed 解释它。

标签: bash unix sed awk


【解决方案1】:

您需要使用\ 转义!

sed "/<\!-- Beginning git log -->/a $log" ~/opt/prime.dropbox/commit.md

【讨论】:

  • 不必在脚本中转义!,只有在交互式运行 bash 时才需要。
【解决方案2】:

为我工作:

$ cat in.txt
some text
<!-- Beginning git log -->
git log output
some text
$ echo $log
[ 2013-08-20 | sergio | git log without -p ] index.html | 2 +- 1 files changed, 1 insertions(+), 1 deletions(-) Yes it looks like.
$ sed "/<\!-- Beginning git log -->/a $log"  in.txt
some text
<!-- Beginning git log -->
[ 2013-08-20 | sergio | git log without -p ] index.html | 2 +- 1 files changed, 1 insertions(+), 1 deletions(-) Yes it looks like.
git log output
some text

【讨论】:

  • 大声笑,是的,当我直接输入 git log 而不是 $log 的输出时,它可以工作。所以... WTF!
【解决方案3】:

sed 是在单行上进行简单替换的出色工具,但对于其他任何事情,只需使用 awk:

awk -v gitlog="$log" '{print} /<!-- Beginning git log -->/{print gitlog}' ~/opt/prime.dropbox/commit.md

在 shell 中运行命令并使用该命令输出安全地覆盖原始文件:

the_command orig_file > /usr/tmp/tmp$$ && mv /usr/tmp/tmp$$ orig_file

在这种情况下:

awk -v gitlog="$log" '{print} /<!-- Beginning git log -->/{print gitlog}' ~/opt/prime.dropbox/commit.md > /usr/tmp/tmp$$ &&
mv /usr/tmp/tmp$$ ~/opt/prime.dropbox/commit.md

临时文件可以在您的工作目录或 $HOME 或 /usr/tmp 或任何您想要的位置,并且可以任意命名。

【讨论】:

  • 好的,谢谢,但它会给我一个“小”错误:awk:运行时错误:无法将命令行分配给日志类型冲突或关键字 FILENAME="" FNR=0 NR=0
  • 天哪。 log 是一个保留变量......也许它甚至可以在 sed 中工作。非常感谢!
  • 不,该错误来自 awk,与 sed 无关。 log 是 awk 函数的名称,这就是为什么您也不能将其用作 awk 变量名称的原因。我应该已经发现了。我更新了我的答案。
  • 我仍然有 awk 的问题,当我运行 bash 时,我可以在终端中看到所做的修改:正是我想要的。但它不会保存在 commit.md 中。不应该吗?
  • 非常感谢,真的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-05
  • 1970-01-01
  • 2013-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-09
相关资源
最近更新 更多