TIL: Using sed to replace text in a file
Published on under the Programming category.Toggle Memex mode
For the last few days, the server on which this website (and many others I run!) started acting strangely. Every so often, nginx would stop working and I'd have to restart the service manually. I had restarted nginx two or three times over the last few days so I knew something wasn't right. I spent some time this afternoon figuring out what was wrong. I found an issue with certbot renewals and nginx that, when resolved, fixed the errors I found in nginx and the /var/log/syslog file on my computer.
Half way through debugging, I noticed that all of my nginx configuration files had certbot directives that pointed to a single SSL certificate -- the one for breakfastand.coffee. I don't know what caused this and I'm not sure how to find out without doing a lot of investigitation into nginx and certbot. If anyone has ever run into this issue, do let me know. I have never seen my nginx certbot directives change to use the same domain name in every file.
Anyway, I had to fix this.
To do so, I thought I could nano into every file and do a find and replace. I had to manually edit between five and ten files though. It wouldn't have been that fun. But, then sed came to mind.
I was reminded of sed lately as I have been learning more about command line scripts. Sed lets you transform text. You can use regular expressions to make a change. With this, I could edit each file without having to nano into the file and make the change.
I wrote a simple sed command:
sed -i 's/breakfastand.coffee/[new-domain-name]/' [config-file-name]
With this command, I could replace the breakfastand.coffee domain with the actual domain name the file should contain. I copy-pasted this for each domain and config file. Then, within barely any time at all, I had fixed the issue and was ready to finish off my debugging.
In short, TIL sed is an incredibly useful tool for text transformations, particularly substitution.
Bonus TIL
Today I also learned about the -n flag to "cat". This flag prints out line numbers at the beginning of each line printed to the console. This command isn't immediately useful to me but I found the command while browsing the sed documentation.
Responses
Comment on this post
Respond to this post by sending a Webmention.
Have a comment? Email me at readers@jamesg.blog.