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

Feature request: Flags for inserting before/after match #201

Open
MaxGyver83 opened this issue Aug 9, 2023 · 1 comment
Open

Feature request: Flags for inserting before/after match #201

MaxGyver83 opened this issue Aug 9, 2023 · 1 comment
Labels
C-enhancement Category: New feature or request

Comments

@MaxGyver83
Copy link

Inserting a multi-line text after a match is not easy with sed.

Example:

$ bat file.txt
───────┬─────────────────────────────────────
       │ File: file.txt
───────┼─────────────────────────────────────
   1   │ first line
   2   │ insert after this line
   3   │ last line
───────┴─────────────────────────────────────

$ echo "$newtext"
  first new line
  second new line

$ bat file.txt | sed "/^insert after this line$/a $newtext"
first line
insert after this line
first new line
last line

Wrong: The first line of the inserted text is not indented. The second line of the inserted text is missing.

This way it works:

$ bat file.txt | sed "/^insert after this line/a \ \ first new line\n  second new line"
first line
insert after this line
  first new line
  second new line
last line

Other idea:

$ bat file.txt | sed "s/(^insert after this line$)/\1$newtext/"
sed: -e expression #1, char 47: unterminated `s' command

sd solution

$ bat file.txt | sd "(^insert after this line$)" "\$1\n$newtext"
first line
insert after this line
  first new line
  second new line
last line

Better than with sed but it could be easier.

Idea:

$ bat file.txt | sd --after "^insert after this line$" "$newtext"

And analogous:

$ bat file.txt | sd --before "^insert before this line$" "$newtext"

Do you think this would be useful? Or would you use the "\$1\n$newtext" solution in such a case?

@CosmicHorrorDev CosmicHorrorDev added the C-enhancement Category: New feature or request label Oct 22, 2023
@dev-ardi
Copy link
Contributor

dev-ardi commented Oct 22, 2023

I think $1\n$newtext is a perfectly good solution

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
C-enhancement Category: New feature or request
Projects
None yet
Development

No branches or pull requests

3 participants