Say I have the following file names from an ls
in a bash script:
things-hd-91-Statistics.db
things.things_domain_idx-hd-38-Data.db
In bash, how would it be able to get the first part of the string 'things'
in either case?
Basically remove the rest of the string past the first -
or .
You should use the charAt() method at index 0 for selecting the first character of the string.
-c (column): To cut by character use the -c option. This selects the characters given to the -c option. This can be a list of numbers separated comma or a range of numbers separated by hyphen(-). Tabs and backspaces are treated as a character.
Another option to determine whether a specified substring occurs within a string is to use the regex operator =~ . When this operator is used, the right string is considered as a regular expression. The period followed by an asterisk . * matches zero or more occurrences any character except a newline character.
You would use parameter expansion:
string="things-hd-91-Statistics.db"
echo "${string%%-*}"
things
Where in ${parameter%%pattern}
the 'pattern' (-*
) is matched against the end of 'parameter'. The result is the expanded value of 'parameter' with the longest match deleted.
Similarly for your other example, the pattern would be %%.*
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