1
$\begingroup$

How do I delete the $n$th line in a multi-line string.

For example how would I delete the $2$nd line in the following string?

multiLineString = "line 1\nline 2\nline 3\nline 4";

enter image description here

such that the output is

"line 1\nline 3\nline 4"

enter image description here

$\endgroup$
1
  • 1
    $\begingroup$ stringDeleteLine[str_, n_] := StringRiffle[Drop[StringSplit[str, "\n"] , {n}] , "\n"] $\endgroup$ Commented May 15, 2021 at 14:47

1 Answer 1

1
$\begingroup$
dropLines = StringRiffle @ Delete[ImportString @ #, #2] &;

Examples:

dropLines[multiLineString, {2}]

enter image description here

dropLines[multiLineString, {{1}, {3}}]

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.