Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
add comment

1 Answer 1

up vote 17 down vote accepted

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
share|improve this answer
    
Thanks, that cleared it to me also. My error was that I understood ! was connected to d, not 123. –  rozcietrzewiacz Nov 18 '11 at 8:44
    
Thanks for your help, Gilles! –  eugene y Nov 18 '11 at 9:05
    
@Gilles: missing the braces {d;q;}, shouldn't q apply to every line (so only the first)? –  enzotib Nov 18 '11 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. –  Gilles Nov 18 '11 at 10:18
    
Crystal clear explanation –  Rahul Patil Jan 24 at 15:44
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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