[Bash] Remove everything after the first space in a string
Solved
Gau36o
Posted messages
14
Status
Member
-
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
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
Problem solved after all...
If it can help someone...
So the truncated result of the variable is stored in $line2
If it can help someone...
line2=$(echo $line1 | cut -d " " -f 1)
So the truncated result of the variable is stored in $line2
Hi,
We can do this as well:
--
_______________________________ ☯ Zen my nuggets ☮ ______________________________
Do a little something for the environment, close your windows and adopt a penguin… 🐧
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… 🐧
Thanks for this answer!
This method suits me much better :)