在文本文件中插入变量

Sam*_*ami 2 bash sed

我正在尝试使用 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)

对这个问题的任何帮助

谢谢

Joh*_*024 6

首先,让我们以更简单的方式定义变量:

$ 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)