[Bash] Remove everything after the first space in a string

Solved
Gau36o Posted messages 14 Status Member -  
Gau36o Posted messages 14 Status Member -
Hello,

Beginner in Bash, I have a string stored in a variable.

For example: maVar="ceci 001 est un exemple 5600"

To remove a strict occurrence such as the ceci (including the space following the word ceci) from the string above, no problem, I do:
line1=${maVar#*ceci }

After this, I would now like to remove the space and everything that follows this space, after the pattern 001. Knowing that 001 is necessarily a group of digits but with a variable length (between 2 and 6 characters).

I tried by doing:
line2=${line1#* }

As well as other attempts, but I can’t get the desired result...

Any help is welcome :-)

Thanks in advance!

Configuration: Windows / Chrome 58.0.3029.110

3 answers

  1. dubcek Posted messages 18627 Registration date   Status Contributor Last intervention   5 660
     
    hello
    or with a table
    $ maVar="ceci 001 est un exemple 5600" 
    $ t=($maVar)
    $ echo ${t[0]}
    ceci
    $ echo ${t[1]}
    001
    2
    1. Gau36o Posted messages 14 Status Member
       
      Hi,
      Thanks for this answer!
      This method suits me much better :)
      0
  2. Gau36o Posted messages 14 Status Member
     
    Problem solved after all...

    If it can help someone...
    line2=$(echo $line1 | cut -d " " -f 1)


    So the truncated result of the variable is stored in $line2
    0
  3. zipe31 Posted messages 34620 Registration date   Status Contributor Last intervention   6 501
     
    Hi,

    We can do this as well:

    $ maVar="ceci 001 est un exemple 5600"

    $ echo "${maVar}"
    ceci 001 est un exemple 5600

    $ echo "${maVar#* }"
    001 est un exemple 5600

    $ echo "${maVar##* }"
    5600

    $ echo "${maVar% *}"
    ceci 001 est un exemple

    $ echo "${maVar%% *}"
    ceci


    --
    _______________________________ ☯ Zen my nuggets ☮ ______________________________
    Do a little something for the environment, close your windows and adopt a penguin… 🐧
    0