12

I've come across this solution for printing a specific line from a text file:

sed '123!d;q' file

Why doesn't sed quit after the first line of input in this case?

1 Answer 1

20

In English, this sed program means: for each line,

  • [123!] if the current line number is not 123, then [d] delete the current line and start the next cycle (i.e. move to the next line);
  • then (but we only reach this point if the d command was not executed), [q] exit without processing any more lines (but do print out the current line in our dying throes).

Or if you prefer, in shell syntax:

line_number=0
while IFS= read -r pattern_space; do
  line_number=$(($line_number+1))
  if [ $line_number -ne 123 ]; then       # 123!
    continue                              #   d
  fi
  echo "$pattern_space"; break            # q
  echo "$pattern_space"                   # implicit final print (never reached)
done
5
  • Thanks, that cleared it to me also. My error was that I understood ! was connected to d, not 123. Commented Nov 18, 2011 at 8:44
  • @Gilles: missing the braces {d;q;}, shouldn't q apply to every line (so only the first)? Commented Nov 18, 2011 at 9:31
  • 1
    @enzotib q applies to every line where it's executed. But when the line number is not 123, the d command is executed, and its meaning is to skip immediately to the next input line. Commented Nov 18, 2011 at 10:18
  • Crystal clear explanation Commented Jan 24, 2014 at 15:44
  • Essentially it does the same as sed -n 123p (prints the same output) except it stops after line 123 rather than processing potentially thousands more lines that it will never do anything with anyways. Commented Feb 15, 2016 at 7:33

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.