嗨,我在用sed命令添加换行符时遇到问题。我被指示编写一个更新主机文件的命令。此外,我的sed命令是用bash脚本编写的,尽管它一直在输出错误消息。上面写着"sed:-e表达式#1,字符93:命令后的额外字符。">
这就是我想添加到主机文件中的内容。
# Gateway
10.0.0.1 schoolhost it20
# Addresses for the Windows
10.0.0.240 host1 it21
10.0.0.241 host2 it22
这是我用bash脚本编写的命令。
sed -i "/hosts/a
n# Gateway
n10.0.0.1 schoolhost it20
n# Addresses for the Windows PCs
n10.0.0.240 host1 it21
n10.0.0.241 host2 it22" hosts
我认为这里不需要sed
。只需使用cat
和此处文档即可。
cat <<EOF >> hosts
# Gateway
10.0.0.1 schoolhost it20
# Addresses for the Windows
10.0.0.240 host1 it21
10.0.0.241 host2 it22
EOF
给定:
$ cat file
line 1
line 2
line 3
和:
$ echo "$add_this"
# Gateway
10.0.0.1 schoolhost it20
# Addresses for the Windows
10.0.0.240 host1 it21
10.0.0.241 host2 it22
您可以做几件事来将这些文本元素添加到一起。
第一种是使用cat
(调用名称来自concattenate(:
$ cat file <(echo "$add_this")
line 1
line 2
line 3
# Gateway
10.0.0.1 schoolhost it20
# Addresses for the Windows
10.0.0.240 host1 it21
10.0.0.241 host2 it22
或者,你可以用同样的方式使用awk
:
$ awk '1' file <(echo "$add_this")
# same output
或者,一个空的sed
:
$ sed -e '' file <(echo "$add_this")
# same output
或使用printf
:
$ printf "%s%sn" "$(cat file)" "$add_this"
# same output
最重要的是,您只需要将两段文本添加到一起,在Unix中有很多方法可以做到这一点。
然后将其中任何一个(可能是cat
(的输出重定向到一个临时文件,然后将该临时文件移动到源文件:
$ cat file <(echo "$add_this") >/tmp/tmp_file && mv /tmp/tmp_file file
$ cat file
line 1
line 2
line 3
# Gateway
10.0.0.1 schoolhost it20
# Addresses for the Windows
10.0.0.240 host1 it21
10.0.0.241 host2 it22