在终端中解析命令的输出

时间:2019-11-13 21:25:19

标签: bash shell terminal

我正在运行heroku命令heroku pg:backups:capture --app appname来备份数据库,该数据库将在终端中返回如下输出:

Use Ctrl-C at any time to stop monitoring progress; the backup will continue running.
Use heroku pg:backups:info to check progress.
Stop a running backup with heroku pg:backups:cancel.

Starting backup of postgresql-xxxxxxxxxx... done
Backing up DATABASE to b007... done

如何将备份名称b007自动存储到变量中?

3 个答案:

答案 0 :(得分:3)

您可以将命令传递给sed以提取所需的字符串:

 dbname=$(heroku pg:backups:capture --app appname | sed -n 's/.*DATABASE to \([^\.]*\)\.\.\..*/\1/p')

答案 1 :(得分:1)

您可以通过管道|将程序的输出重定向到

grep "Backing up DATABASE to " | awk '{print substr($5,0,5)}'

应该是:

var=$(heroku pg:backups:capture --app appname | grep "Backing up DATABASE to " | awk '{print substr($5,0,5)}')

答案 2 :(得分:0)

简单化的可能性:

while read -r line
do echo "$line"
   case "$line" in
   Backing\ up\ DATABASE\ to\ *done)
       backup="${line%%... done}"
       backup="${backup##* }"
   esac
done < <( heroku pg:backups:capture --app appname )
echo "Backup: [$backup]"