Home > Blockchain >  Awk get all text within start and end keys
Awk get all text within start and end keys

Time:03-18

I have the following output from man df

DF(1)                             User Commands                            DF(1)

NAME
       df - report file system space usage

SYNOPSIS
       df [OPTION]... [FILE]...

DESCRIPTION
       This manual page documents the GNU version of df.  df displays the amount
       of space available on the file system containing each file name argument.
       If  no  file  name is given, the space available on all currently mounted
       file systems is shown.  Space is shown in 1K blocks  by  default,  unless
       the  environment  variable POSIXLY_CORRECT is set, in which case 512-byte
       blocks are used.

       (continues)

I want to awk this output such that I get only the lines starting with NAME and ending right before DESCRIPTION, like so:

NAME
       df - report file system space usage

SYNOPSIS
       df [OPTION]... [FILE]...

What would the pattern expression look like for this?

CodePudding user response:

This displays everything between lines starting with "NAME" and lines starting with "DESCRIPTION".

man df | awk '/^NAME/{f=1}/^DESCRIPTION/{f=0}f'

CodePudding user response:

I would use GNU AWK for this task following way

man df | awk '/^DESCRIPTION/{exit}/^NAME/,0{print}'

Explanation: If line starts with DESCRIPTION exit (end processing) starting from line starting which starts with NAME and up to 0 print line. Note that 0 is never true, so it will print everything up to line starting with DESCRIPTION.

(tested in gawk 4.2.1)

CodePudding user response:

You can do:

man df | awk -v RS= -v ORS='\n\n' 'NR==2 || NR == 3'
NAME
       df - report file system space usage

SYNOPSIS
       df [OPTION]... [FILE]...

When RS is set to the empty string, each record always ends at the first blank line encountered See awk manual: https://www.gnu.org/software/gawk/manual/html_node/Multiple-Line.html

  • Related