Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I would like to use sed to search for the first part of a text file with consecutive lines with at least n non-space characters. I would like to print from the first of those lines to the end of the file.

What's the best way to formulate this?

share|improve this question
up vote 2 down vote accepted

With sed, this should work:

sed -ne "/\([^[:blank:]].*\)\{$n\}/!d;h;n;//!d;x;p;x;:1" -e 'p;n;b1'
share|improve this answer
Thank you. This works. – dan Sep 17 '12 at 21:51
awk -v n=$n ' 
    !p {line = $0; gsub(/[[:space:]]/, "")}  
    !p && length($0) >= n && prev_is_long {p = 1; print prev}  
    !p {prev = line; prev_is_long = (length($0) >= n)}  
    p {print} 
' file1 
share|improve this answer
This almost works, but it seems to smoosh together the words of the first line shown. – dan Sep 17 '12 at 21:07
@dan I think this should do it. – Gilles Sep 17 '12 at 23:47

I know you said sed (no pun intended) but if you can live with PERL, the following should do what you want (n=20):

#!/usr/bin/perl -w
my $n=20;    ## The minimum length of the line
my $prev=""; ## This holds the number of chars in the previous line
my $pline;   ## This holds the previous line
my $pp=0;    ## Counter, lines will be printed if set to 1
    ## Skip line processing if we have already 
    ## found our lines of interest
    $pp==1 && do {print; next};
    ## Get non-space chars
    my $a=join("",/[^\s]+/g);
    ## Print if requirements are met.
    if (length($prev)> $n && length($a)> $n){
    print $pline,$_;

Save it as foo.pl and run like so:

$ perl foo.pl infile.txt
share|improve this answer

Your Answer


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.