在sed中匹配的模式之后添加一行不起作用

时间:2015-06-28 03:24:17

标签: regex linux sed pam

我的/etc/pam.d/system-auth-ac设置了以下auth个参数:

auth        required      pam_env.so
auth        sufficient    pam_unix.so nullok try_first_pass
auth        requisite     pam_succeed_if.so uid >= 500 quiet
auth        required      pam_deny.so

我想在pam_tally2.so之后插入pam_env.so。所以我希望它是:

auth        required      pam_env.so
auth        required      pam_tally2.so onerr=fail audit silent deny=5 unlock_time=900
auth        sufficient    pam_unix.so nullok try_first_pass
auth        requisite     pam_succeed_if.so uid >= 500 quiet
auth        required      pam_deny.so

我正在使用的脚本是:

#! /bin/bash

grep "pam_tally2" /etc/pam.d/system-auth-ac &> /dev/null
if [ $? -ne 0 ];
then
   sed -i '/^[]*account[]*required[]*pam_unix.so/aauth\trequired\tpam_tally2.so onerr=fail audit silent deny=5 unlock_time=900' /etc/pam.d/system-auth-ac
else
   sed -i 's/.*pam_tally2.*/auth\trequired\tpam_tally2.so onerr=fail audit silent deny=5 unlock_time=900/1' /etc/pam.d/system-auth-ac
fi

但它给出了这个错误:

sed: -e expression #1, char 116: unterminated address regex

我做错了什么?

3 个答案:

答案 0 :(得分:2)

您可以在gnu-sed中使用a命令:

sed -i.bak '/pam_env\.so$/a\
auth        required      pam_tally2.so onerr=fail audit silent deny=5 unlock_time=900
' /etc/pam.d/system-auth-ac

编辑:查看您发布的答案,awk命令似乎比grep中的sed和2 if/else命令更适合您条件:

val='auth\trequired\tpam_tally2.so onerr=fail audit silent deny=5 unlock_time=900'
awk -v val="$val" '/^auth[[:blank:]]+required[[:blank:]]+pam_env\.so/ {
   print $0 RS val; next} /pam_tally2\.so/{next} 1' /etc/pam.d/system-auth-ac

auth        required      pam_env.so
uth         required      pam_tally2.so onerr=fail audit silent deny=5 unlock_time=900
auth        sufficient    pam_unix.so nullok try_first_pass
auth        requisite     pam_succeed_if.so uid >= 500 quiet
auth        required      pam_deny.so

答案 1 :(得分:1)

您可以使用以下sed命令。

sed 's/^auth[[:blank:]]\+required[[:blank:]]\+pam_env\.so/&\nauth        required      pam_tally2.so onerr=fail audit silent deny=5 unlock_time=900' file

你的正则表达式失败了,因为你重复了一个空字符类[],零次或多次,这没有任何意义。因此,您需要将[]*更改为[ ]*<space>*以重复零空格或空格的空格字符。

答案 2 :(得分:0)

我的剧本应该是:

false

工作正常!