我正在尝试使用 sed -i 命令在文本文件的第一行中插入一个字符串变量。此命令有效:sed -i '1st header' file.txt
但是当我传递一个变量时,这不起作用。例子 :
var=$(cat <<-END
This is line one.
This is line two.
This is line three.
END
)
sed -i '1i $var' file.txt # doesn't work
sed -i ’1i $var’ file.txt # doesn't work
Run Code Online (Sandbox Code Playgroud)
对这个问题的任何帮助
谢谢
首先,让我们以更简单的方式定义变量:
$ var="This is line one.
This is line two.
This is line three."
Run Code Online (Sandbox Code Playgroud)
由于 sed 不擅长处理变量,让我们使用 awk。这会将您的变量放在文件的开头:
awk -v x="$var" 'NR==1{print x} 1' file.txt
Run Code Online (Sandbox Code Playgroud)
-v x="$var"
这定义了一个 awk 变量x以具有 shell 变量的值$var。
NR==1{print x}
在第一行,这告诉 awk 插入变量的值x。
1
这是 awk 对 print-the-line 的简写。
让我们定义你的变量:
$ var="This is line one.
> This is line two.
> This is line three."
Run Code Online (Sandbox Code Playgroud)
让我们处理这个测试文件:
$ cat File
1
2
Run Code Online (Sandbox Code Playgroud)
这是 awk 命令产生的结果:
$ awk -v x="$var" 'NR==1{print x} 1' File
This is line one.
This is line two.
This is line three.
1
2
Run Code Online (Sandbox Code Playgroud)
要file.txt使用最近的 GNU awk 进行原地更改:
awk -i inplace -v x="$var" 'NR==1{print x} 1' file.txt
Run Code Online (Sandbox Code Playgroud)
在 macOS、BSD 或更旧的 GNU/Linux 上,使用:
awk -v x="$var" 'NR==1{print x} 1' file.txt >tmp && mv tmp file.txt
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4726 次 |
| 最近记录: |