简体   繁体   中英

Combine output from two commands into single table with shell script

I want to display the output of the following commands which are as below-:

1)

mount | grep -i "/dev/sd*" | awk '{ print NR "\t" $1 "\t" $3 }'

2)

/usr/sbin/smartctl -a /dev/sdb | grep Device: | awk '{print $2 }'

The 1st comand displays 3 columns with multiple rows and the next command displays one one column of information.

I want to concat the outputs of both the commands and concat and display as 4 columns with multiple rows. Please suggest.

This is what paste is for. Use process substitution to make the shell treat your commands like files:

paste <(mount | awk 'tolower($0) ~ /\/dev\/sd*/ {print NR "\t" $1 "\t" $3}') \
      <(/usr/sbin/smartctl -a /dev/sdb | awk '/Device:/ {print $2}')

I removed the grep commands, which awk can easily do.

Make a named pipe to hold the first command's output:

mkfifo mount_output
mount | grep -i "/dev/sd.*" | awk '{ print NR "\t" $1 "\t" $3 }' > mount_output &

Then use paste :

/usr/sbin/smartctl -a /dev/sdb | grep Device: | awk '{print $2 }' | paste foo -

Note that awk '{print $2 }' can be simplified to cut -d' ' -f2 . Making a temporary named pipe is more properly done with

tempd=`mktemp -d`
mkfifo ${tempd}/mount_output

then rm -rf "$tempd" when the pipe is no longer needed.

Some thoughts:

If you've already got awk in your command line, you don't really need grep. So you can do this:

mount | awk '/\/dev\/sd/ {print NR, $1, $3}'
smartctl -a /dev/sdb | awk '/Device:/ {print $2}'

If you want to produce one line of output for each device, you can pipe the output of your first command line into a loop, and then run smartctl inside the loop, like this:

mount | awk '/\/dev\/sd/ {print NR, $1, $3}' | while read nr dev mntpt; do
  echo -e "$nr\t$dev\t$mntpt\t$(smartctl -a $dev | awk '/Device:/ {print $2}')"
done

The -e flag to echo is necessary to make it recognize \\t as a tab character.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM