简体   繁体   中英

How can I use 'sed' in a Linux Bash script file to comment out a particular line with tabbed spacing?

I wish to add '#' to the beginning of this line within a particular file using sed. The script will be run within a .sh file, not typed into the console.

auth    [success=1 default=ignore]      pam_unix.so nullok_secure

Should be:

#auth    [success=1 default=ignore]      pam_unix.so nullok_secure

I'm currently trying commands similar to:

sudo sed -e '/auth[[:tab:]][success=1[[:space:]]default=ignore][[:tab:]]pam_unix.so[[:space:]]nullok_secure/ s/^#*/#/' -i /etc/pam.d/common-auth

I know the above command is wrong, as [[:tab:]] is not a valid command. I just want to show where the tabs occur.

Any help is appreciated!!! Thanks!!!

On Ubuntu you can use \\t for tab, and I believe that's even specified in POSIX.

/auth\t\[success=1 default=ignore\]\tpam_unix.so nullok_secure/

I think I've run into issues doing that on BSD though, but if you don't really care that it's exactly a tab, and would accept the line even if it has other types of spaces you could be a little more flexible

/auth[[:space:]]\+\[success=1 default=ignore\]pam_unix.so[[:space:]]nullok_secure/

which is a GNU-ism for the \\+ to mean one or more of the previous, to be more POSIX-y you could do it

/auth[[:space:]][[:space:]]*\[success=1 default=ignore\]pam_unix.so[[:space:]]nullok_secure/

(And note that the [:space:] character class does not contain only the space character, it's the set of white space characters, which includes tabs.)

Also note, we have to escape the [ in the pattern you're matching, or it will define a character class of things to match, which is certainly not what you're trying for here.

As another option, assuming your common-auth looks like mine, that's the only line that has success=1 on it so you could just use that, although it's more fragile if other people make changes to the file some time.

It works...

sed -e '/^auth\t\[success=1\ default=ignore\]\tpam_unix.so\ nullok_secure/ s/^/#/' -i file

I'm just using \\t instead of [[:tab:]]

And \\ instead of [[:space:]]

You're making this very hard on yourself. The authconfig files are standard and won't need all of the regex you're using.

sed -i 's/^auth    [success=1 default=ignore]      pam_unix.so nullok_secure/#auth    [success=1 default=ignore]      pam_unix.so nullok_secure/' /etc/pam.d/common-auth

If you really want to be specific though, I wouldn't use the space and tab lookups. Just look for the text you want and the white space in between.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM