Grep for unix semicolons

I am trying to get disk information from fdisk -loutput in linux.

fdisk -l | grep -E 'Disk /dev/sd.\:'

I get the following output.

Disk /dev/sde doesn't contain a valid partition table
Disk /dev/sda: 1000.2 GB, 1000204886016 bytes
Disk /dev/sdb: 1000.2 GB, 1000204886016 bytes

but i want to get

Disk /dev/sda: 1000.2 GB, 1000204886016 bytes
Disk /dev/sdb: 1000.2 GB, 1000204886016 bytes

I tried to do it

fdisk -l | grep -E 'Disk /dev/sd.\:' | grep -v "contain" 

but I have no idea why grep does not ignore the line containing "contain".

+3
source share
3 answers

Try the following command:

fdisk -l 2>/dev/null | grep -E 'Disk /dev/sd.\:'

Or simply:

fdisk -l 2>/dev/null

The problem is that the string is Disk /dev/sde doesn't contain a valid partition tablegenerated as an error and written to stderrinstead stdout.

The pipe in the output is for UNIX-only channels, written to stdoutfrom the previous command with the command on the RHS channel, so your grep command works only on the 2nd and 3rd lines, and the 1st line on your terminal comes from stderr.

+3
source

grep , "no valid partition" stderr. stderr stdout, grep. .

, csh/tcsh:

  fdisk -l |& grep -E 'Disk /dev/sd.\:' | grep -v "contain"

/bash:

  fdisk -l 2>&1 | grep -E 'Disk /dev/sd.\:' | grep -v "contain"

. / stderr /dev/null , ( ) . stderr stdout .

0

All unix commands have two outputs; stderr and stdout. Errors are printed on stderr and normal output on stdout. In your example, you can send stderr to / dev / null to get rid of the extra line. Like this:

fdisk -l 2>/dev/null

0
source

All Articles