2

I want to read a value from a known file.

File is located at /root/.my.cnf and contains

[client]
password='PosftGlK2y'

I would like to return PosftGlK2y - ideally using a simple one liner command.

I have tried

cat /root/.my.cnf | grep password

which returns password='PosftGlK2y'

I am sure there is a better way.

2
  • 1
    You don't need to use cat -- grep could read the file. That's call UUoC (Useless Use of cat). Commented Jun 9, 2015 at 0:26
  • 1
    To parse anything sophisticated enough, you probably don't want to reinvent the wheels but instead get a decent INI parser. Commented Jun 9, 2015 at 0:27

2 Answers 2

2

You can skip the cat and grep directly, and then pipe to awk with a ' delimiter.

grep password /root/.my.cnf | awk -F"'" '{print $2}'

Alternately, you can skip the grep altogether and just use awk to do the search and the extraction.

awk -F"'" '/^password=/{print $2}' /root/.my.cnf
Sign up to request clarification or add additional context in comments.

7 Comments

@CharlesDuffy, Sure, I'll add that in.
awk -F"'" ' /^password=/{print $2}' </root/.my.cnf
And the selection might be better anchored to the start of the line and followed by an =, so you might have awk '/^password=/ { ... }'
...of course, it's an issue if the file happens not to be written with single quotes.
This also will match any comments in the file containing the word "password", as currently written.
|
1

You could use cut to split the line on the ' character:

grep password= /root/.my.cnf | cut -d "'" -f 2

returns

PosftGlK2y

The cut command splits a line on the delimiter (-d flag) and returns the column(s) specified by the f flag.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.