A common way for Shell to intercept strings

Source: Internet
Author: User
Tags first string truncated

1, get the character from the front 8, the implementation method is as follows:

a=123456789

$ expr substr $a 1 8

$ echo $a |cut-c 1-8echo $

$ echo $a |dd Bs=1 count=8 2>/dev/null



2. Interception by the specified string


(1) The first method:


A string after the last string is truncated from left to right

${varible##*string}

A string after the first string is truncated from left to right

${varible#*string}

A string after the last string is intercepted from right to left

${varible%%string*}

A string after the first string is intercepted from right to left

${varible%string*}


such as ip=192.168.1.1, install "." Segmentation

$ echo ${ip##*.} #得到的是最后一列

1

$ echo ${ip#*.} #得到的除去第一列的字符串

168.1.1


$ echo ${ip%%.*} #得到的是第一列

192

$ echo ${ip%.*} #得到的除去最后一列的字符串

192.168.1


3, get the specified length


${VARIBLE:N1:N2}: Intercepts the variable varible the N2 character starting from N1, forming a substring. You can select specific substrings by using a different form of variable extension, depending on the specific character offset and length. Try entering the following line in bash:

such as ip=192.168.1.1

$ echo ${ip:0:3}

192

$ echo ${ip:3}

.168.1.1



4. Gets the specified column

such as ip=192.168.1.1

$ echo $ip | Cut-d "."-f2

168

$ echo $ip |  Awk-f "." ' {print $} '

168


Reference: http://54rd.net/html/2015/shell_0423/110.html


This article from "Small Fish Blog" blog, declined reprint!

A common way for Shell to intercept strings

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.