Svan Svan - 1 month ago 6
Bash Question

bashscript extract info from custom row

under command :gpart show

i get the output
=> 34 31457213 ada0 GPT (15G)
34 128 1 freebsd-boot (64k)
162 29360000 2 freebsd-ufs (14G)
29360162 1572864 3 freebsd-swap (768M)
30933026 524221 - free - (10GB)


how can i extract just 14G from 3rd line and 10GB from last line?

the 14/10GB values are never the same, which makes my work harder to do.

i manage to get some results using

cat test | sed 's/\|/ /' | awk '{print $6}{print $5}'
but i still have to extract just that info,

any ideas? please thanks.

Answer

With awk:

awk -F '[()]' 'NR==3 {print $(NF-1)} END{print $(NF-1)}' file.txt
  • -F '[()]' sets the field delimiter as ( or )

  • NR==3 {print $(NF-1)} prints the desired field for the third line

  • END{print $(NF-1)} prints the desired field for the last line

Example:

% cat file.txt
    34  31457213  ada0  GPT  (15G)
        34       128     1  freebsd-boot  (64k)
       162  29360000     2  freebsd-ufs  (14G)
  29360162   1572864     3  freebsd-swap  (768M)
  30933026    524221        - free -  (10GB)

% awk -F '[()]' 'NR==3 {print $(NF-1)} END{print $(NF-1)}' file.txt
14G
10GB