Print the entire variable if the number of lines is greater than N

How to print all lines if a certain condition is met.

Example:

echo "$ip"
this is a sample line
another line
one more
last one

      

If this file has more than 3 lines, print the entire variable.

I am tried:

echo $ip| awk 'NR==4' 
last one
echo $ip|awk 'NR>3{print}' 
last one

echo $ip|awk 'NR==12{} {print}' 
this is a sample line
another line
one more
last one

echo $ip| awk 'END{x=NR} x>4{print}' 

      

It is necessary to achieve this:

If the file contains more than three lines, print the entire file. I can do it with wc

and bash

, but you need one liner.

+3


source to share


3 answers


You can use Awk

like this:

echo "$ip" | awk '{a[$0]; next}END{ if (NR>3) { for(i in a) print i }}'
one more
another line
this is a sample line
last one

      

you can also change the value 3

from a variable Awk

,

echo "$ip" | awk -v count=3 '{a[$0]; next}END{ if (NR>count) { for(i in a) print i }}'

      

The idea is to store the contents of each line in {a[$0]; next}

as each line is processed, by the time the sentence is reached the END

variable NR

will have the number of lines of the line / file you have. Print lines if the condition matches a number greater than 3

or any other configurable value.



And always remember to cast variables to in a nutshell bash

to avoid word breaks done by the shell.


Using James Brown's helpful comment below to preserve line order, do

echo "$ip" | awk -v count=3 '{a[NR]=$0; next}END{if(NR>3)for(i=1;i<=NR;i++)print a[i]}'
this is a sample line
another line
one more
last one

      

+2


source


The correct way to do it (no echo, no channel, no loops, etc.):



$ awk -v ip="$ip" 'BEGIN{if (gsub(RS,"&",ip)>2) print ip}'
this is a sample line
another line
one more
last one

      

+3


source


Another in awk. First test files:

$ cat 3
1
2
3
$ cat 4
1
2
3
4

      

code:

$ awk 'NR<4{b=b (NR==1?"":ORS)$0;next} b{print b;b=""}1' 3  # look ma, no lines
  [this line left intentionally blank. no wait!]
$ awk 'NR<4{b=b (NR==1?"":ORS)$0;next} b{print b;b=""}1' 4
1
2
3
4

      

Clarifications:

NR<4 {                     # for tghe first 3 records
    b=b (NR==1?"":ORS) $0  # buffer them to b with ORS delimiter
    next                   # proceed to next record
} 
b {                        # if buffer has records, ie. NR>=4
    print b                # output buffer
    b=""                   # and reset it
}1                         # print all records after that

      

+1


source







All Articles