bonnithedog
bonnithedog

Reputation: 11

Get first characters to a variable

I have an output like this

I need to get the id 65a8fa6 as an variable to a new command.

I'm familiar with grep and use it to get the line I need. But how do I only pick the first 7 caracters.

This is where I'm now

vagrant global-status | grep  DB1

Output

65a8fa6  default vmware_desktop running     /Users/USER/Documents/Vagrant/centos7SN/DB1 

Upvotes: 1

Views: 906

Answers (3)

DivDiff
DivDiff

Reputation: 983

You can also use the cut command to find instances of what you're after, provided that there's some consistent text near what you want to find:

Say you want to find Hello out of the following line:

Hello  here's some text blablablabla

You can find it doing something like:

echo Hello  here's some text blablablabla | grep text | cut -d "  " -f 1

Should output Hello

Upvotes: 0

Raman Sailopal
Raman Sailopal

Reputation: 12887

Sed alternative:

val=$(vagrant global-status | sed -rn 's/(^[[:alnum:]]{7})(.*$)/\1/p')

Split the output of vagrant ... into two sections using sed and regular expressions (-r) Substitute the line for the first section only and print.

Upvotes: 0

RavinderSingh13
RavinderSingh13

Reputation: 133680

1st solution: You could simply do this with awk. Simply look for string DB in line and then if its found then print 1st field of that line. Save the output into variable var and later you could use it for your use.

val=$(vagrant global-status | awk '/DB1/{print $1}')

OR for matching either db1 OR DB1 try in any awk:

val=$(vagrant global-status | awk '/[dD][bB]1/{print $1}')


2nd solution: If you have GNU awk and you want to use ignorecase then try:

val=$(vagrant global-status | awk -v IGNORECASE="1" '/DB1/{print $1}')


3rd solution: To get first 7 characters try:

But how do I only pick the first 7 characters.

val=$(vagrant global-status | awk '/[dD][bB]1/{print substr($0,1,7)}')

Upvotes: 1

Related Questions