Linux ‘sed’ command

sed (stream editor) is a Unix utility that parses and transforms text, using a simple, compact programming language.
sed was based on the scripting features of the interactive editor ed (“editor”, 1971) and the earlier qed (“quick editor”, 1965–66).
sed was one of the earliest tools to support regular expressions, and remains in use for text processing, most notably with the substitution command.Other options for doing “stream editing” include AWK and Perl.

Say in the below scenario, we wanted to comment all the “setParameter” configurations in mongod.conf file.
Instead of doing it manually using the vi editor, we can use ‘sed’ command as below.

[root@hostname etc]# cat mongod.conf
# Security
auth = true
setParameter = supportCompatibilityFormPrivilegeDocuments=0
setParameter = authenticationMechanisms=GSSAPI,MONGODB-CR
setParameter = logUserIds=1
#sslOnNormalPorts = true
#sslPEMKeyFile = /etc/ssl/mongodb.pem
#sslPEMKeyPassword = pass
[root@hostname etc]#

‘sed’ command for it as below.

[root@hostname etc]# sed “s/setParameter/#setParameter/g” mongod.conf | grep set
#setParameter = supportCompatibilityFormPrivilegeDocuments=0
#setParameter = authenticationMechanisms=GSSAPI,MONGODB-CR
#setParameter = logUserIds=1
[root@hostname etc]#

To use multiple modifications, we can use “;” as below

[root@hostname etc]# sed “s/setParameter/#setParameter/g;s/auth/#auth/g” mongod.conf
# Security
#auth = true
#setParameter = supportCompatibilityFormPrivilegeDocuments=0
#setParameter = #authenticationMechanisms=GSSAPI,MONGODB-CR
#setParameter = logUserIds=1
#sslOnNormalPorts = true
#sslPEMKeyFile = /etc/ssl/mongodb.pem
#sslPEMKeyPassword = pass
[root@hostname etc]#

To modify in the file directly, we can use -i option as below

[root@hostname etc]# sed -i “s/setParameter/#setParameter/g;s/auth/#auth/g” mongod.conf

[root@hostname etc]# grep “setParameter” mongod.conf
#setParameter = supportCompatibilityFormPrivilegeDocuments=0
#setParameter = #authenticationMechanisms=GSSAPI,MONGODB-CR
#setParameter = logUserIds=1
[root@hostname etc]#

  • Ask Question