Shell string manipulation

Source: Internet
Author: User

First, the environment

ubuntu14.04 x86_64

Second, string manipulation

1. get the string length

Strlen () similar to the C language

${#variable_name}

Eg:

$name =zhangsan$echo ${#name}8$

2. String Extraction

Similar to substring () in Java

${variable_name:start_index:length} from left to right , starting with section Start_index (0), the length of the substring
${variable_name:0-start_pos:length} Starting from the end the number of Start_pos, length of the substring

eg

$echo ${name:0:4}zhang$echo ${name:2} #从第二个位置开始, to the end Angsan$echo ${name:0-4:2}gs$echo ${name:0-4} #从倒数第4开始, to the end

3. String interception

Delete from left to right

${variable_name#*separator} separator is the character you want to separate, to the position of the first separator

STRCHR () similar to the C language

eg

$name =zhangsan-lisi-wangwu-baidi$echo ${name#*-}lisi-wangwu-baidi$

${variable_name##*separator} to the last separator position.

Rindex () similar to the C language

eg

$echo ${name##*-}baidi$

Delete from right to left

${variable_name%separator*}

${variable_name%%separator*}

eg

$echo ${name%-*} Zhangsan-lisi-wangwu$echo ${name%%-*}zhangsan$

4. String splitting

C language-like strtok ()

${variable_name//ch/ch_replace} replaces the character ch in variable_name with the ch_replace character

eg

$name =zhangsan-lisi-wangwu-baidi$name=${name//-/,} #将横杠替换为逗号 $echo ${name}zhangsan,lisi,wangwu,baidi$name={name// ,/} #将逗号替换为空格 $echo ${name}zhangsan Lisi Wangwu Baidi #可用于后续的for循环 $

IFS is split by setting the value of IFS


eg

$test =aaa,bbb,ccc,ddd,eee$arr=${test} $echo ${arr}aaa,bbb,ccc,ddd,eee$old_ifs= $IFS $ifs=, $arr 2=${test} $echo ${arr2 }AAA BBB CCC DDD Eee$ifs=${old_ifs}



This article is from the "Snow Dancer" blog, please be sure to keep this source http://happytree007.blog.51cto.com/6335296/1904950

Shell string manipulation

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.