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 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
add comment

3 Answers 3

up vote 2 down vote accepted

With sed, this should work:

n=5
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
add comment

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
while(<>){
    ## 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,$_;
    $pp=1;
    }
    $prev=$a;
    $pline=$_;
}

Save it as foo.pl and run like so:

$ perl foo.pl infile.txt
share|improve this answer
add comment
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
1  
@dan I think this should do it. –  Gilles Sep 17 '12 at 23:47
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.