【问题标题】:sed match pattern with multi line string in a variablesed 匹配模式与变量中的多行字符串
【发布时间】:2018-01-18 21:20:45
【问题描述】:

我阅读了很多答案和示例,但找不到匹配的示例,因为我也找不到 sed。这是我想要做的:

sftp_configuration_lines="Match User ${sftp_username}
ForceCommand internal-sftp
PasswordAuthentication yes
ChrootDirectory /home/${sftp_username}
PermitTunnel no
AllowAgentForwarding no
AllowTcpForwarding no
X11Forwarding no

"

    sed -i -e "s|${sftp_configuration_lines_sed}|#removed|g" /etc/ssh/sshd_config;

当然这个不工作,并给出一个未终止的命令错误。

我已经在行尾用 \ 和 \n 尝试过,但仍然没有运气。我在这里错过了什么?

【问题讨论】:

  • 您好@Edvin,感谢您的友好评论,但我没有在任何地方使用单引号,您可以使用不同的分隔符,例如 /,#,|只要它们的顺序正确。

标签: regex bash ubuntu sed ubuntu-16.04


【解决方案1】:

您可以将awk 与空的RS 一起使用,而不是sed

sftp_configuration_lines="Match User ${sftp_username}
ForceCommand internal-sftp
PasswordAuthentication yes
ChrootDirectory /home/${sftp_username}
PermitTunnel no
AllowAgentForwarding no
AllowTcpForwarding no
X11Forwarding no"

awk -v RS= -v s="$sftp_configuration_lines" '{gsub(s, "#removed")} 1' /etc/ssh/sshd_config

或者,你也可以使用perl

perl -0777 -pe "s~$sftp_configuration_lines~#removed~" /etc/ssh/sshd_config

【讨论】:

  • 我不知道为什么但不工作。会不会少了点什么?
  • 查看我的更新,如何设置sftp_configuration_lines。确保sshd_config 中的文本完全相同,否则请尝试我的perl 解决方案。
  • 仍然无法正常工作。我决定采用另一种方法。
【解决方案2】:

这种方法适合您吗?在这种情况下,您只需遍历您的模式并逐行删除。

 declare -a patterns=( "Match User ${sftp_username}" "ForceCommand internal-sftp" "PasswordAuthentication yes" "ChrootDirectory /home/${sftp_username}" "PermitTunnel no" "AllowAgentForwarding no" "AllowTcpForwarding no" "X11Forwarding no" );

 for pattern in "${patterns[@]}"
 do
     sed -i  -e "s|${pattern}|#removed|g"  /etc/ssh/sshd_config;

 done

希望这有助于解决您的问题。

您好!

注意:我假设你在“$sftp_username”中有一些东西,如果你没有并且你实际上试图替换文字字符串,只需将数组声明中的“for”更改为这样:

  declare -a patterns=( 'Match User ${sftp_username}' "ForceCommand internal-sftp" "PasswordAuthentication yes" 'ChrootDirectory /home/${sftp_username}' "PermitTunnel no" "AllowAgentForwarding no" "AllowTcpForwarding no" "X11Forwarding no" );

【讨论】:

    猜你喜欢
    • 2020-04-06
    • 1970-01-01
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    • 2020-11-14
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    相关资源
    最近更新 更多