0

I am actually learning about sed command tutorial , where I am running below command in order to print the line 1st,4th,7th,10th,13th ..... line from Notes.txt. I am using MAC terminal

sed -n '1~3p' Notes.txt

I am facing below issue while running above command. Any help will be more appreciated.

sed: 1: "1~3p": invalid command code ~

1 Answers1

4

The ADDR1,~N range address syntax is a non-standard extension introduced by the GNU implementation of sed. The sed implementation found on macos is or is derived from that of FreeBSD and doesn't support that extension.

You can however use perl or awk instead:

perl -ne 'print if $. % 3 == 1'
awk 'NR % 3 == 1'

With standard sed syntax, you can also do:

sed -n 'p;n;n'

Where n;n consumes 2 lines without printing them after each printed one.

See also:

sed -n 'N;N;P'

which pulls the Next two lines into the pattern space and then Prints the first.

That one behaves differently if the input has a number of lines that is not a multiple of 3 though:

$ seq 10 | sed -n 'p;n;n'
1
4
7
10
$ seq 10 | sed -n 'N;N;P'
1
4
7

Upon reaching the 10th line, N failed causing sed to exit which meant P was not run.