Technorati tags: String, Bash, expr
Search for the length of the substring expr match "string" 'string '. Here, the substring is a regular expression. For example, if expr match "abcdefg123456" '[A-Z] * [0-9]', 8 is returned. The regular expression [A-Z] * [0-9] matches abcdefg1, so the length is 8.
Extract the substring expr substr string POS Len. This is equivalent to substr () in STD: string of C ++ (). The difference is that the subscript of POS starts from 1, and the subscript of STD: String starts from 0. For example, expr substr "abcdefg123456" 1 6, the extracted substring is abcdef, starting from the first one with a length of 6.
In fact, the string operation functions in bash are rich and diverse. For example, the length of the substring is written in another way: expr "$ string": '$ substring '. The extracted substrings are also $ {string: Position} and $ {string: Position: length. These different forms of string operations are both convenient and confusing. In advanced bash scripting guide, it is called "bash supports a surprising number of string manipulation operations. unfortunately, these tools lack a uniied focus. some are a subset of parameter substitution, and others fall under the functionality of the UNIX expr command. this results in inconsistent command syntax and overlap of functionality, not to mention confusion."
The following code copies all *. PNG files in the current state of ABC123 to a new place and uses ABC as the directory. Here ''is the key on the tab, which represents the expression value. It can be used to assign the return value in'' to the variable.
1: For a in $ (ls $ srcdir)
2: Do
3: Len = 'expr match "$ A" '[A-Z] * [0-9]''
4: Len = $ ($ len-1 ))
5: Echo $ Len
6: B = 'expr substr $ A 1 $ len'
7: Echo $ A to $ B
8: mkdir-p $ dstdir/$ B
9: CP $ srcdir/$ A/maps/*. PNG $ dstdir/$ B/
10: Done
Ref: http://tldp.org/LDP/abs/html/string-manipulation.html