sd icon indicating copy to clipboard operation
sd copied to clipboard

Feature request: ability to exit after one replacement

Open ngirard opened this issue 5 years ago • 4 comments

I ran against this situation multiple times: I only need to search & replace the first occurrence of a pattern.

It'd be useful if sd allowed to exit gracefully after performing one replacement.

There would be 2 benefits:

  • better performance/efficiency;
  • safety, as it would prevent unwanted replacements.

ngirard avatar Oct 23 '20 16:10 ngirard

Why only the first? Maybe better - or somewhat "complete" - exit after m matches/replacements, default=1

sklages avatar Nov 19 '20 11:11 sklages

@sklages, sure.

I just meant to illustrate that this feature request originated from a specific, real-world situation of mine.

ngirard avatar Nov 19 '20 12:11 ngirard

So https://github.com/chmln/sd/commit/687f3a5b1463886b0cbe926253497fd7c6ae447b has been merged, and has added a -n flag, however it doesn't work, -n1 -n 1 -n=1 all error with:

error: Found argument '-n' which wasn't expected, or isn't valid in this context
> sd --version
sd 0.7.6

balupton avatar Dec 02 '21 06:12 balupton

It would be cool if the occurrence flag allowed a range, such that this becomes much easier:

echo $'a\nb\nc\na\nb\nc' | sd -n 2, '(?m:\nb$)' '' | sd '^b$' 'B'

To get back:

a
B
c
a
c

balupton avatar Dec 02 '21 07:12 balupton

Great that -n max was added in v1.0.0 🎉

Note that the range suggestion (as teip does) has not been added: https://github.com/greymd/teip/issues/27

For me, this is my use case that I want to simplify:

https://github.com/bevry/dorothy/blob/de23d08e4cb7cc7823b8638a479d86831d8f2bf8/commands/config-helper#L341-L367

balupton avatar Nov 10 '23 16:11 balupton