Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the first part of the string in bash

Tags:

substring

bash

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 .

like image 609
chiappone Avatar asked Oct 07 '12 05:10

chiappone


People also ask

How do I get the first letter of a string in Linux?

You should use the charAt() method at index 0 for selecting the first character of the string.

How do I cut a specific string in Linux?

-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.

How do I find a character in a string in bash?

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.


1 Answers

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 %%.*

like image 99
jasonwryan Avatar answered Nov 15 '22 06:11

jasonwryan