sed Sanitize Muti-Line Substitution

时间:2014-08-14 15:07:12

标签: bash sed

我正在尝试完成以下任务:

sed "s/{{HELP}}/$(dist/forge-cli.phar --no-ansi)/g" < post-build-hooks/readme.md.template > readme.md

此处的目标是从dist/forge-cli.phar获取结果,该结果显示该命令的帮助页面,并将其写入我的readme.md文件。但是,我收到以下错误:

sed: 1: "s/{{HELP}}/Console Tool ...": unescaped newline inside substitute pattern

dist/forge-cli.phar的输出包含多行。输出在这里:

Console Tool

Usage:
  [options] command [arguments]

Options:
  --help           -h Display this help message.
  --quiet          -q Do not output any message.
  --verbose        -v|vv|vvv Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug
  --version        -V Display this application version.
  --ansi              Force ANSI output.
  --no-ansi           Disable ANSI output.
  --no-interaction -n Do not ask any interactive question.

Available commands:
  cake             ??
  daemons          List the daemons configured by Forge
  env              Get a list of Environment Variables
  firewall         Get the public and private IPs for this server
  git              Displays details about a site's git repository.
  help             Displays help for a command
  ip               Get the public and private IPs for this server
  jobs             List the scheduled jobs configured by Forge
  keys             List the SSH Keys configured by Forge
  list             Lists commands
  monitoring       Describe Monitoring Services configured by Forge
  self-update      Update Forge CLI
  sites            List the sites configured by Forge
daemon
  daemon:restart   Restart a daemon
  daemon:status    Get the status of a daemon
log
  log:daemon       Get the latest log for a daemon
  log:deploy       Get the latest deploy log
  log:job          Get the latest log for a scheduled job

所以这是最后一个问题。我怎样才能消毒&#34;我的phar命令的输出是否正确地为sed命令转义它?

2 个答案:

答案 0 :(得分:1)

使用以下命令工作!

sed "s/{{HELP}}/$(dist/forge-cli.phar --no-ansi | gsed "s/$/\\\/g") /g" post-build-hooks/readme.md.template > readme.md

答案 1 :(得分:1)

假设{{HELP}}在文件中位于其自己的行上,您可以使用awk执行此操作:

awk -v h="$(dist/forge-cli.phar --no-ansi)" '/{{HELP}}/{print h;next}1' in > out

当输入文件中匹配/{{HELP}}/时,请打印变量h的内容,然后跳到下一行。否则,最后的1只表示awk打印该行。

这只需要调用awk一次并打印h的内容,无论它是否包含shell可能解释的任何其他字符。

相关问题