Get second column of line with certain text from command output directly

时间:2018-01-11 08:46:04

标签: linux bash shell

I'm trying to extract the text in second column of multiple line command output.

The command shows an output like this.

Nginx configuration  wp basic (enabled) 
PHP Version      7.0    
HHVM             disabled    
SSL          enabled    
SSL PROVIDER             Lets Encrypt    
SSL EXPIRY DATE          Wed Apr 11 06:29:29 UTC 2018

access_log       /var/www/website.com/logs/access.log    
error_log        /var/www/website.com/logs/error.log    
Webroot          /var/www/website.com    
DB_NAME          certainDBName    
DB_USER          certainDBUser    
DB_PASS          passwordString

I want to read the DB_PASS line from command output and extract the passwordString to a variable, directly from my first command output without writing to a file.

3 个答案:

答案 0 :(得分:3)

使用单个 awk 命令:

pass_str=$(awk '/^DB_PASS/{ print $2; exit }' file)
$ echo "$pass_str" 
passwordString

答案 1 :(得分:3)

您可以使用awk

轻松完成
awk '$1=="DB_PASS" { print $2 }' test.log > output.txt

这意味着在列1等于" DB_PASS"的行中打印第2列。假设您的结果位于test.log文件

答案 2 :(得分:2)

您可以使用@RomanPerekhrest建议的awk或使用sed

sed -n 's/DB_PASS \(.*\)/\1/p' <youfile>