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 ~
4
  • then if I am using MAC terminal , then what command I need to use Commented Jan 21, 2024 at 7:36
  • You may be able to install gsed with brew - see for example Is it possible to get GNU sed for OSX? Commented Jan 21, 2024 at 14:33
  • ... see also Differences between sed on Mac OSX and other "standard" sed? Commented Jan 21, 2024 at 14:33
  • It might be due to how the command is interpreted in your specific shell or environment. However, the command itself is correct. I expect you mean the range of 1,4,7,10... Commented Jan 21, 2024 at 16:13

1 Answer 1

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.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.