我有一些$f类似于以下内容的文本文件
function
%blah
%blah
%blah
code here
Run Code Online (Sandbox Code Playgroud)
我想在第一个空行之前附加以下文本:
%
%This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike
%3.0 Unported License. See notes at the end of this file for more information.
Run Code Online (Sandbox Code Playgroud)
我尝试了以下方法:
top=$(cat ./PATH/text.txt)
top="${top//$'\n'/\\n}"
sed -i.bak 's@^$@'"$top"'\\n@' $f
Run Code Online (Sandbox Code Playgroud)
其中第二行(我认为)保留文本中的新行,第三行(我认为)用文本加上新的空行替换第一个空行。
两个问题:
1-我的代码附加以下文本:
%n%本作品根据 Creative Commons Attribution-NonCommercial-ShareAlike n%3.0 Unported License 获得许可。有关详细信息,请参阅此文件末尾的注释。\n
2- 将其附加到文件末尾。
有人可以帮助我理解我的代码的问题吗?
如果您正在使用GNU sed,则以下操作可行。
用于^$查找空行,然后用于sed替换/放置所需的文本。
# Define your replacement text in a variable
a="%\n%This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike\n%3.0 Unported License. See notes at the end of this file for more information."
Run Code Online (Sandbox Code Playgroud)
注意,$a应该包括那些\n将被直接解释为sed换行符的内容。
$ sed "0,/^$/s//$a/" inputfile.txt
Run Code Online (Sandbox Code Playgroud)
在上面的语法中,0代表第一次出现。
输出:
function
%blah
%blah
%
%This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike
%3.0 Unported License. See notes at the end of this file for more information.
%blah
code here
test
Run Code Online (Sandbox Code Playgroud)