1

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
eifersucht
  • 661
  • 8
  • 26

3 Answers3

3

With single awk command:

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

$ echo "$pass_str" 
passwordString
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
3

You can easily do it using awk

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

This means print column 2 in the row where column 1 is equals to "DB_PASS" assuming your result is in a test.log file

rakwaht
  • 3,666
  • 3
  • 28
  • 45
  • 1
    +1 Hmmm, I believe this is the most ideal way of doing it :-) But the op doesn't wish the result to be written to a file. Instead you should use the command substitution `$()` feature to write the results into a variable. – sjsam Jan 11 '18 at 09:04
  • 1
    Yes but I think it can be easily turned in a command that take input from a pipe and save it to a variable, I am giving an idea not coding for you guys :) – rakwaht Jan 11 '18 at 09:06
  • Can i use this command using my info command as an input on the fly? Instead of writing the first output to a file? – eifersucht Jan 11 '18 at 09:55
2

You can use awk as proposed by @RomanPerekhrest or use sed

sed -n 's/DB_PASS \(.*\)/\1/p' <youfile>
ezdazuzena
  • 6,120
  • 6
  • 41
  • 71
  • This will work, but as You and I know this is the hard way of doing it. The `awk` is better suited for this kind of job. You might want to add a `--` after the `-n` so that you could also accept the filenames starting with dashes like `-my-file`. – sjsam Jan 11 '18 at 09:02
  • @sjsam hehe.. yes, we do. It was the first that came to my mind answer. I left the answer because it's always good to see more than one solution – ezdazuzena Jan 11 '18 at 09:21