Substring in linux using cut

I would like to grab a substring of a file to get the default password of mysql in centos. This is the command I am using to get the password:

sudo grep 'temporary password' /var/log/mysqld.log

which result is:

2018-02-21T07:03:11.681201Z 1 [Note] A temporary password is generated for root@localhost: >KkHAt=#z6OV

Now, I am using this command to get the password only and remove the unnecessary stuff, so I can use it in a script:

sudo grep 'temporary password' /var/log/mysqld.log | cut -d ':' -f 4 | cut -d ' ' -f 2

But using 2 cuts seems very ugly. Is there another command or tool that I can use, or a more elegant way to do this?

Upvotes: 0

Views: 457

Answers (2)

wchmb
wchmb

Reputation: 1354

Bearing in mind that awk splits the lines in fields based on a field separator (by default whitspaces) and NF refers to the number of fields, you can print the last field with:

$ grep 'temporary password' /var/log/mysqld.log | awk '{print $NF}'

Upvotes: 0

James Brown
James Brown

Reputation: 37464

Using awk:

$ awk '/temporary password/{print $NF}' file
>KkHAt=#z6OV

Upvotes: 3

Related Questions