sed:在 <HEAD> 部分结束前插入文本

Gam*_*per 5 osx sed text-processing

我需要在本HEAD节结束之前将一些文本插入到 HTML 文件中。

我想:

sed -i "s#</head>#<style> @page { prince-shrink-to-fit: auto }
.repository-with-sidebar.with-full-navigation .repository-content 
{width: 950px ! important;} </style>\n</head>#" ${1}"/"${2}"/"${i}.html
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:

sed: 1: command a expects \ followed by text
Run Code Online (Sandbox Code Playgroud)

我只是没有看到我的错误。我什至尝试在样式周围使用单引号。

我想在本HEAD节末尾插入的确切文本是:

<style>
@page { prince-shrink-to-fit: auto }
.repository-with-sidebar.with-full-navigation .repository-content 
{width: 950px ! important;}
</style>
Run Code Online (Sandbox Code Playgroud)

编辑:这是确切的命令:

sed -i "s#</head>#<style> @page { prince-shrink-to-fit: auto } .repository-with-sidebar.with-full-navigation .repository-content {width: 950px ! important;} </style>\n</head>#" ${1}"/"${2}"/"${i}.html
Run Code Online (Sandbox Code Playgroud)

编辑 2:为了尝试确保我正确格式化命令,我也在尝试这个:

strToInsert='<style> @page { prince-shrink-to-fit: auto } .repository-with-sidebar.with-full-navigation .repository-content {width: 950px ! important;} </style>'

sed -i "s#</head>#$strToInsert\n</head>#" ${1}"/"${2}"/"${i}.html
Run Code Online (Sandbox Code Playgroud)

这让我意识到我插入的文本可能有问题。

Mic*_*mer 4

In-placesed过程中需要制作备份文件。-iApple 上的选项sed需要一个扩展参数(用于它创建的备份文件)并使用下一个参数。这意味着您告诉它您希望它创建一个扩展名为“ #s</head>#...”的备份文件。

该错误意味着它认为您指的是apend command。我猜测 的值$1以 开头a。因为-iate 前面的参数sed认为这是要运行的脚本,而不是要更改的文件的路径,因此您会收到相应的错误。这正是您在 Applesed和无效a命令时会遇到的错误:

$ sed a
sed: 1: "a": command a expects \ followed by text
Run Code Online (Sandbox Code Playgroud)

-i在命令中提供扩展参数sed:

sed -i.bak "s#</head>#<style> @page { prince-shrink-to-fit: auto } .repository-with-sidebar.with-full-navigation .repository-content {width: 50px ! important;} </style>\n</head>#" "${1}/${2}/${i}.html"
Run Code Online (Sandbox Code Playgroud)

并且事情会起作用(尽管请注意这\n不是换行符转义)。如果使用单引号,甚至可以去掉“”中的空格!important。

上面的代码也适用于 GNU sed,但请注意,这-i不是 POSIX 选项,并且通常不可移植。

通常建议无论如何都不要使用就地修改,并自己明确地处理文件副本。不过,这取决于你。


您应该引用变量扩展${1}等。仅引用斜杠是没有意义的,因为它们始终是文字。