我想从 test.txt 中获取前两行:
hello
my
name
is
Run Code Online (Sandbox Code Playgroud)
并将它们放在新文件 output.txt 的顶部:
foo
bar
Run Code Online (Sandbox Code Playgroud)
所需的输出为output.txt:
hello
my
foo
bar
Run Code Online (Sandbox Code Playgroud)
使用 sed。但是,使用:
text=$(head test.txt -n 2) | sed -i "1i $text" output.txt
Run Code Online (Sandbox Code Playgroud)
返回错误:
sed: -e expression #1, char 10: extra characters after command
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
首先,您不必在变量赋值text=和sed命令之间使用管道。您需要替换为命令分隔符;。
其次,您可能会收到错误,因为部分替换文本是由 解释的sed。您实际上需要引用替换字符串。bash这可以通过参数扩展运算符来完成@Q。
text=$(head -n2 test.txt)
sed -i "1i ${text@Q}" output.txt
Run Code Online (Sandbox Code Playgroud)
正如bash手册页中提到的:
${parameter@operator}
...
Q 扩展是一个字符串,它是以可重复用作输入的格式引用的参数值。
显然,在第 1 行之前插入与执行以下操作相同:
head -n2 text.txt > /tmp/temp.txt
cat output.txt >> /tmp/temp.txt && mv /tmp/temp.txt ouput.txt
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7373 次 |
| 最近记录: |