Can’t figure out how to split a mutliline string on %%
#11769
-
I write some great fish aliases and forget to use them, so I wanted something that would remind me. I asked ChatGPT to whip something up and I've been trying to get the function in a shape that I'd like. However, my biggest problem is that neither I nor it can find a way to split a string properly. Here's the script itself: function __tip_of_the_day --description 'Show a (fish) tip-of-the-day'
set -l tips_file ~/.config/fish/tips.txt
test -f $tips_file; or return
set -l content (string collect < $tips_file)
set --show content
set -l tips (string split0 --no-empty -- "\n%%\n" -- $content)
set -l count (count $tips)
test $count -gt 0; or return
set --show tips
for i in (seq (count $tips))
printf '--- tip %d start ---\n%s\n--- tip %d end ---\n' $i $tips[$i] $i
end
set -l today (date "+%Y-%m-%d")
if not command -q sha256sum; echo "__tip_of_the_day: need sha256sum" >&2; return; end
set -l sha (printf "%s" $today | sha1sum)
printf "sha: %s\n" "$sha"
set -l hex8 (string sub --start 1 --length 8 -- "$sha")
printf "hex8: %s\n" "$hex8"
set -l num (math "0x$hex8")
printf "num: %s\n" $num
set -l idx (math "($num % $count) + 1")
printf "idx: %s\n" $idx
set -l tip "$tips[$idx]"
set_color brcyan
echo "# Tip of the day"
set_color normal
echo
printf "%s\n" "$tip"
echo
end And here's the contents of
And here's what I get when I run it today (August 31, 2025):
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment · 1 reply
-
If you change line 7 from set -l tips (string split0 --no-empty -- "\n%%\n" -- $content) to set -l tips (string split --no-empty -- \n"%%"\n $content) it will work as you intend it to. Or at least the tips part will, I'm not entirely certain if the sha part will, as I don't actually have Three things with that line:
You might also want to remove the blank lines before and after the |
Beta Was this translation helpful? Give feedback.
If you change line 7 from
to
it will work as you intend it to. Or at least the tips part will, I'm not entirely certain if the sha part will, as I don't actually have
sha256sum
on the system I'm using and couldn't test that part. I do have asha256
andsha1
, and just substituting those always returned whatever was in index 2 for me. I'm unsure if those commands are equivalent, though. I'm running it on OpenBSD, and not sure if I could get sha1sum - a quick package scan didn't turn anything up.Three things with that line:
split
notsplit0
.split0
does …