sed

How to remove the Nth line from a file

Easy solution with sed:

$ sed --in-place '3d' test.txt

sed: working with multi-line patterns

Sed principally works with single lines.

To allow multi-line replacements, use the N option.
sed 'N; s/from\ncontinued/from...continued/' file.txt

Removing all the new lines:
sed ':a;N;$!ba;s/\n/ /g'

With perl

One can achieve the same with perl:
perl -0pe 's/from\n/to/' file.txt
where -0 tells perl to match NUL character instead of new lines.

sed: -e expression #1, char NN: unknown option to `s'

Error:

sed: -e expression #1, char 49: unknown option to `s'

Example code producing this error:
sed "s/<[^<]*example.com[^>]*>\([^<]*\)</a>/\1/g"

Solution:
check for un-escaped forward slashes. Above, the slash in </a> is unescaped. Everything coming after the third slash is considered to be options for s, like the final 'g' is intended to be.
Either escape the slashes:

sed "s/<[^<]*example.com[^>]*>\([^<]*\)<\/a>/\1/g"

Or use a different delimiter, e.g. '#':

sed "s#<[^<]*example.com[^>]*>#([^<]*\)#\1/g"

sed: -e expression #1, char 0: no previous regular expression

Error:

sed: -e expression #1, char 0: no previous regular expression

Seen while testing with empty replacement strings:
sed "s///"

"//" refers to a non-existent previously-compiled regular expression.

sed: how to show what has changed

Both in piped content and with --in-line, how to show exactly what has changed with sed?

Maybe with a wrapper script that shows nice coloured output for changes?

sed: can't read : No such file or directory

Error message:

sed: can't read : No such file or directory

This is due to running sed with the option --in-place without having a given file:

$ sed --in-place s/from/to/ ""

In a bash script

This error is usually encountered when sed is employed within a bash script. For example:

#!/bin/bash
sed --in-place "s/from/to/" "${1}"

and forgetting to run the script with a file argument:
$ myscript.sh
sed: can't read : No such file or directory
$ myscript.sh file.txt # OK.

Syndicate content