如何提取和解析shellscript命令到文件?

时间:2016-11-14 13:16:59

标签: bash shell heroku append string-concatenation

我在Shell Script中有以下程序:

#!/bin/sh

max=9
for i in `seq 1 $max`
do
    sudo -u ${USERNAME} heroku config --app mws-usp-app0${i}
done

max=50
for i in `seq 10 $max`
do
    sudo -u ${USERNAME} heroku config --app mws-usp-app${i}
done

for命令的每一行的结果是:

=== mws-usp-app01 Config Vars
CLEARDB_DATABASE_URL:         mysql://<user>:<password>@<hostname>/<defaultschema>?reconnect=true
DATABASE_URL:                 postgres://...:...@ec2-23-21-73-32.compute-1.amazonaws.com:5432/dalmmfh5cs6nqa
HEROKU_POSTGRESQL_PURPLE_URL: postgres://...:...@ec2-50-19-219-148.compute-1.amazonaws.com:5432/de4hk500aj9f1q
JAVA_OPTS:                    -XX:+UseCompressedOops
=== mws-usp-app02 Config Vars
CLEARDB_DATABASE_URL:         mysql://<user>:<password>@<hostname>/<defaultschema>?reconnect=true
DATABASE_URL:                 postgres://...:...@ec2-23-21-73-32.compute-1.amazonaws.com:5432/dalmmfh5cs6nqa
HEROKU_POSTGRESQL_PURPLE_URL: postgres://...:...@ec2-50-19-219-148.compute-1.amazonaws.com:5432/de4hk500aj9f1q
JAVA_OPTS:                    -XX:+UseCompressedOops
...
=== mws-usp-app50 Config Vars
CLEARDB_DATABASE_URL:         mysql://<user>:<password>@<hostname>/<defaultschema>?reconnect=true
DATABASE_URL:                 postgres://...:...@ec2-23-21-73-32.compute-1.amazonaws.com:5432/dalmmfh5cs6nqa
HEROKU_POSTGRESQL_PURPLE_URL: postgres://...:...@ec2-54-243-204-86.compute-1.amazonaws.com:5432/d5gngl61fsq95o
JAVA_OPTS:                    -XX:+UseCompressedOops 

如何解析CLEARDB_DATABASE_URL以获取<user><password><hostname><defaultschema>的所有值并将其放入文本文件中?

======================================

响应后的正确脚本:

#!/bin/sh

max=9
for i in `seq 1 $max`
do
    echo "mws-usp-app0${i}";
    sudo -u ${USERNAME} heroku config --app mws-usp-app0${i} | sed -n 's/CLEARDB_DATABASE_URL.*mysql:\/\/\(.*\):\(.*\)@.*/\1 \2/p' >> usernames.txt
done

max=50
for i in `seq 10 $max`
do
    echo "mws-usp-app${i}";
    sudo -u ${USERNAME} heroku config --app mws-usp-app${i} | sed -n 's/CLEARDB_DATABASE_URL.*mysql:\/\/\(.*\):\(.*\)@.*/\1 \2/p' >> usernames.txt
done
$> chmod +x script.sh
$> sudo ./script.sh

1 个答案:

答案 0 :(得分:1)

假设您的输出位于名为input.txt的文件中,您可以使用sed:

  sed -n 's/CLEARDB_DATABASE_URL.*mysql:\/\/\(.*:.*\)@.*/\1/p' input.txt > usernames.txt

或者立即使用shell脚本的输出:

  <your_script> | sed -n 's/CLEARDB_DATABASE_URL.*mysql:\/\/\(.*:.*\)@.*/\1/p' > usernames.txt

可能有一种更简单的方法,但那是我心中最快的东西;)