skip to Main Content

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 

3

Answers


  1. 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)}')
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search