【问题标题】:appending new line with sed command in bash在 bash 中使用 sed 命令添加新行
【发布时间】:2018-12-03 08:11:15
【问题描述】:

您好,我无法通过 sed 命令添加换行符。我被指示编写一个更新主机文件的命令。另外,我的 sed 命令是用 bash 脚本编写的,尽管它一直输出错误消息。它说“sed: -e expression #1, char 93: extra character after command.”

这是我想添加到我的主机文件中的内容。

# 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

【问题讨论】:

  • 您只需要将这些确切的行附加到主机文件吗?
  • 是的,即使是评论。主机文件的原始内容只有“localhost”。这个脚本假设更新它。它更像是一个备份脚本。
  • 将您的文件上传到某处并发布链接。
  • ufile.io/9l5d4 用于 host_update。 ufile.io/5hn8pfor主机文件
  • 您已使用 Windows 系统创建或编辑过该文件。

标签: bash sed text-processing


【解决方案1】:

我认为这里不需要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

【讨论】:

    【解决方案2】:

    给定:

    $ 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%s\n" "$(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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-25
      • 1970-01-01
      • 2011-04-28
      • 1970-01-01
      • 2016-11-06
      • 1970-01-01
      • 2016-08-26
      相关资源
      最近更新 更多