[英]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) 1)
mount | grep -i "/dev/sd*" | awk '{ print NR "\t" $1 "\t" $3 }'
2) 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. 第一个命令显示3列多行,下一个命令显示一列信息。
I want to concat the outputs of both the commands and concat and display as 4 columns with multiple rows. 我想连接命令和concat的输出,并显示为4列多行。 Please suggest.
请建议。
This is what paste
is for. 这就是
paste
的用途。 Use process substitution to make the shell treat your commands like files: 使用进程替换使shell将命令视为文件:
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. 我删除了grep命令,awk很容易做到。
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
: 然后使用
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
. 请注意,
awk '{print $2 }'
可以简化为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. 然后当不再需要管道时
rm -rf "$tempd"
。
Some thoughts: 一些想法:
If you've already got awk in your command line, you don't really need grep. 如果你已经在命令行中使用了awk,那么你真的不需要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: 如果要为每个设备生成一行输出,可以将第一个命令行的输出传递到循环中,然后在循环内运行smartctl,如下所示:
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. -e
标志要使echo识别\\t
作为制表符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.