Intro To Sed
Another useful linux tool is sed which stands for stream editor and is used to perform text transformations on an input stream which can be a file or input from a pipe. By default sed outputs everything to standard out so you need to direct the output to a file if that is what you want. Let’s jump into some examples.
In our Github repository we have a default template for writing our social posts. As part of that template we want a dynamic date that sets the current date:
Using sed we can dynamically update that date string to include the current date:
Which will output:
Unsure about the pbcopy and pbpaste above. Check out post Copying & Pasting In CLI With pbcopy & pbpaste.
In our case we’re call a bash script so the sed instructions are a bit different because we need to write to a file and want to edit the file in place. Our bash script looks like this:
We use the -i
flag which is equivalent ti --in-place
and we pass an empty string
as the backup location which is the “zero length extension” for backup which basically
means don’t create a backup and write directly to a file.
If you’re on mac vs. linux it might be worth reading up on the differences between Mac OSX sed and other standard sed: Differences between sed on Mac OSX and other “standard” sed?
Read more about it here and Digital Ocean has a nice overview on sed as well. If you’re looking to get deep into sed, check out the Grymoire sed guide