I call a dictionary file from my nupass.nu password generator command, which is simply a file with one Japanese word or phrase per line. I wanted to be able to easily add words to the dictionary file, followed by a quick git commit, hence this nushell
script.
In this case, it's easy to just add those commands to nushell
's env.nu
instead of having them as a separate script file. Once added, I just reloaded nushell
, and then it was just a matter of doing the following to add the words to the file:
> dict add onepiece golgo13 dragonball naruto doraemon
See the screenshot below for what the output looks like.
A couple notes:
- calls an environment variable "DICT_FILE_PATH" as default for the dict file path. Set it in
env.nu
like this:let-env DICT_FILE_PATH = '/path/to/where/dict/file/lives/'
- in the flags definition section, uses a "rest parameter" (
...word
) to accept any number of words, and allows you to override the path - uses a
for
loop to loop over the word or words in$word
, checking if the word is already present or not, making lists of added and not added words, and passing any not-yet-present words to a utility functionappend_file
to add to the dict - since the words are appended to the end of the file and I'd like them sorted alphabetically, the script then opens the file, switches to lines, removes any dupes with
uniq
, sorts alphabetically, then overwrites the file - checks the lists of added or not added words, and displays messages depending on whether a word was added or skipped, creating a git commit string and committing to git as needed
- to create a list of words for the commit message, I thought I needed to use
reduce
and an accumulator, but it's more simple to usestr join
for that.
You can use a similar technique in nushell
anytime you need to add strings to a file, whether they are words, commands, paths etc. Enjoy.
- @melMass - for the help in figuring out appending with a newline and the advice to separate it into a utility command, then for the proposal on how to improve the script. :)