How can I remove parts of a string up to a certain character?
Ex.) If I have the string testFile.txt.1
and testFile.txt.12345
how can I remove the 1
and 12345
?
EDIT: I meant to remove and throw away the first part of a string up to a certain character and keep the end of it.
Using the parameter expansion syntax To remove the first and last character of a string, we can use the parameter expansion syntax ${str:1:-1} in the bash shell. 1 represents the second character index (included). -1 represents the last character index (excluded).
As $machinenumber that is used has to have a leading zero in it for other purposes, the idea is simply to create a new variable ( $nozero ) based on $machinenumber , where leading zeros are stripped away. $machinetype is 74 for now and hasn't caused any problems before.
Using the cut Command You can also use the -d and -f flags to extract a string by specifying characters to split on. The -d flag lets you specify the delimiter to split on while -f lets you choose which substring of the split to choose.
The tr command (short for translate) is used to translate, squeeze, and delete characters from a string. You can also use tr to remove characters from a string. For demonstration purposes, we will use a sample string and then pipe it to the tr command.
using just bash facilities
$ s=testFile.txt.1
$ echo ${s%.*}
testFile.txt
$ s=testFile.txt.12345
$ echo ${s%.*}
testFile.txt
to remove before leading zero
$ echo ${s#*.}
txt.12345
Other method, you can split your string up using IFS
$ s=testFile.txt.12345
$ IFS="."
$ set -- $s
$ echo $1
testFile
$ echo $2
txt
$ echo $3
12345
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With