Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add an option to string collect to preserve everything except the final newline #10064

Open
IsaacOscar opened this issue Oct 20, 2023 · 1 comment

Comments

@IsaacOscar
Copy link

IsaacOscar commented Oct 20, 2023

Bassically, consider the following code:

program $variable

This works exactly as I would expect.
But suppose I first want to replace all occurences of foo with bar before calling program, naturally I tried this:

program (string replace -a "foo" "bar" $variable)

Now it works most of the time, but not if $variable contains a newline, in which case it actually passes multiple arguments to foo, none of which contain newlines.

So I tried using string collect:

program (string replace -a "foo" "bar" $variable | string collect)

Which almost works! The newlines are preserved, unless $variable ends in a newline, in which case it is striped.

So next I tried using the --no-trim-newlines option to string collect:

program (string replace -a "foo" "bar" $variable | string collect -N)

Unfortunately now program always gets an extra newline (since string replace itself keeps outputing one). I want the argument to program to end in a newline if and only if $variable does.

Eventuallly, I found a solution that almost works:

program (string replace -a "foo" "bar" $variable | head -c -1 | string collect -N)

Another solution is to use something other than string replace:

program (echo -n $variable | sed 's/foo/bar/g' | string collect -N)

Unfortunatly that doesn't work if $variable is the empty string, because then program get's no arguments. I also have to pass the --allow-empty option to string collect.

My point is that I think it would be very helpfull if string collect had an option that did this (and/or an option to string replace and other builtins to not print newlines I never asked for).

@lavafroth
Copy link
Contributor

lavafroth commented Jan 22, 2024

You could try something like this:

program "$(string replace "foo" "bar" $variable)"

Here's what I tried:

Setting the variable:

set variable "this is some example text
with some newlines
hehe"

Replacing "some" with "THE":

printf "$(string replace "some" "THE" $variable)"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants