Warm tip: This article is reproduced from serverfault.com, please click

replacing whole, first matched line

发布于 2020-11-29 14:14:06

Input file:

auth        sufficient    pam_unix.so nullok try_first_pass abcderf

Though, the regex seems to be correct and working, sed command does not replace matched line:

regex'es tried successfully:

$ grep -E '[[:space:]]*auth[[:space:]]+sufficient[[:space:]]+pam_unix.+$' input
auth        sufficient    pam_unix.so nullok try_first_pass abcderf
$ grep -E '^\s*auth\s+sufficient\s+pam_unix\.so.*$' input
auth        sufficient    pam_unix.so nullok try_first_pass abcderf
$ grep -E "^\s*auth\s+sufficient\s+pam_unix\.so.*$" input
auth        sufficient    pam_unix.so nullok try_first_pass abcderf

However, sed commands using above regex don't replace matched line as expected, with content of P variable:

$ P='auth        sufficient    pam_unix.so nullok try_first_pass'

$ echo "$P"
auth        sufficient    pam_unix.so nullok try_first_pass

$ sed "0,/^\s*auth\s+sufficient\s+pam_unix\.so.*$/s//${P}/" input|grep -E '^\s*auth\s+sufficient\s+pam_unix\.so.*$'
auth        sufficient    pam_unix.so nullok try_first_pass abcderf

$ sed "0,/^[[:space:]]*auth[[:space:]]+sufficient[[:space:]]+pam_unix.*$/s//${P}/" input|grep -E '^\s*auth\s+sufficient\s+pam_unix\.so.*$'
auth        sufficient    pam_unix.so nullok try_first_pass abcderf
Questioner
Chris
Viewed
0
KamilCuk 2020-11-29 23:11:16

In basic regex + is +. To match one or more characters in basic regex you have to \+.

sed "0,/^[[:space:]]*auth[[:space:]]\+sufficient[[:space:]]\+pam_unix.*$/s//${P}/"
# I would keep it in ' quotes
sed '0,/^[[:space:]]*auth[[:space:]]\+sufficient[[:space:]]\+pam_unix.*$/s//'"${P}"'/'

But you might as well use sed -r or sed -E and use extended regex with sed, as you seem to use \s extensions anyway.