A detailed approach to shell string interception _linux Shell

Source: Internet
Author: User
Tags first string

The first 8 bits of a character variable are intercepted by the Linux shell, with the following methods:

Copy Code code as follows:

1.expr substr "$a" 1 8
2.echo $a |awk ' {print substr (, 1,8)} '
3.echo $a |cut-c1-8
4.echo $
5.expr $a: ' (. \). * '
6.echo $a |dd Bs=1 count=8 2>/dev/null

Second, intercept by the specified string
1, the first method:
${varible##*string} to intercept the string after the last string from left to right
${varible#*string} to intercept the string after the first string from left to right
${varible%%string*} to intercept the string after the last string from right to left
${varible%string*} to intercept the string after the first string from right to left
"*" is just a wildcard character that you can not

Example:

Copy Code code as follows:
$ myvar=foodforthought.jpg
$ echo ${myvar##*fo}
Rthought.jpg
$ echo ${myvar#*fo}
Odforthought.jpg

2, the second method: ${varible:n1:n2}: Intercept the variable varible from N1 to N2 between the string.

You can select a specific substring by using a variable extension of another form, depending on the specific character offset and length. Try entering the following line in bash:

Copy Code code as follows:
$ exclaim=cowabunga
$ echo ${exclaim:0:3}
Cow
$ echo ${exclaim:3:7}
Abunga

This form of string truncation is simple, with a colon separated to specify the starting character and substring length.

Divided according to the specified requirements:
Like getting the suffix name

Copy Code code as follows:
Ls-al | Cut-d "."-f2

Application Experience:

Copy Code code as follows:

$MYVAR = "12|DADG"
Echo ${myvar##*|} #打印分隔符后的字符串
Dafa
Echo ${myvar%%|*} #打印分隔符前的字符串
12

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.