Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 变量中具有多行字符串的sed匹配模式_Regex_Bash_Ubuntu_Sed_Ubuntu 16.04 - Fatal编程技术网

Regex 变量中具有多行字符串的sed匹配模式

Regex 变量中具有多行字符串的sed匹配模式,regex,bash,ubuntu,sed,ubuntu-16.04,Regex,Bash,Ubuntu,Sed,Ubuntu 16.04,我读了很多答案和例子,但找不到匹配的例子,因为我也找不到sed。以下是我想做的: sftp_configuration_lines="Match User ${sftp_username} ForceCommand internal-sftp PasswordAuthentication yes ChrootDirectory /home/${sftp_username} PermitTunnel no AllowAgentForwarding no AllowTcpForwarding no

我读了很多答案和例子,但找不到匹配的例子,因为我也找不到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,但仍然没有成功。我这里缺少什么?

您可以将
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

这种方法适合你吗?在本例中,您只需迭代模式并逐行删除

 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”:
您好@Edvin,谢谢您的评论,但我没有在任何地方使用单引号,您可以使用不同的delimeters,如/、#、|,只要顺序正确。我不知道为什么,但不起作用。可能缺少什么吗?请参阅我的更新,如何设置
sftp\u配置行
。确保中有完全相同的文本de>sshd\u config否则请尝试我的
perl
解决方案。仍然不起作用。我决定采用另一种方法。
  declare -a patterns=( 'Match User ${sftp_username}' "ForceCommand internal-sftp" "PasswordAuthentication yes" 'ChrootDirectory /home/${sftp_username}' "PermitTunnel no" "AllowAgentForwarding no" "AllowTcpForwarding no" "X11Forwarding no" );