In bash shell, when you use a dollar sign followed by a variable name, shell expands the variable with its value. This feature of shell is called parameter expansion.

But parameter expansion has numerous other forms which allow you to expand a parameter and modify the value or substitute other values in the expansion process. In this article, let us review how to use the parameter expansion concept for string manipulation operations.

This article is part of the on-going bash tutorial series. Refer to our earlier article on bash { } expansion.

1. Identify String Length inside Bash Shell Script

${#string}

The above format is used to get the length of the given bash variable.

$ cat len.sh
#! /bin/bash var="Welcome to the geekstuff" echo ${#var} $ ./len.sh

To understand more about bash variables, read 6 Practical Bash Global and Local Variable Examples.

2. Extract a Substring from a Variable inside Bash Shell Script

Bash provides a way to extract a substring from a string. The following example expains how to parse n characters starting from a particular position.

${string:position}

Extract substring from $string at $position

${string:position:length}

Extract $length of characters substring from $string starting from $position. In the below example, first echo statement returns the substring starting from 15th position. Second echo statement returns the 4 characters starting from 15th position. Length must be the number greater than or equal to zero.

$ cat substr.sh
#! /bin/bash var="Welcome to the geekstuff" echo ${var:}
echo ${var::} $ ./substr.sh
geekstuff
geek

Also, refer to our earlier article to understand more about $*, $@, $#, $$, $!, $?, $-, $_ bash special parameters.

3. Shortest Substring Match

Following syntax deletes the shortest match of $substring from front of $string

${string#substring}

Following syntax deletes the shortest match of $substring from back of $string

${string%substring}

Following sample shell script explains the above two shortest substring match concepts.

$ cat shortest.sh
#! /bin/bash filename="bash.string.txt" echo ${filename#*.}
echo ${filename%.*} $ ./shortest.sh
After deletion of shortest match from front: string.txt
After deletion of shortest match from back: bash.string

In the first echo statement substring ‘*.’ matches the characters and a dot, and # strips from the front of the string, so it strips the substring “bash.” from the variable called filename. In second echo statement substring ‘.*’ matches the substring starts with dot, and % strips from back of the string, so it deletes the substring ‘.txt’

4. Longest Substring Match

Following syntax deletes the longest match of $substring from front of $string

${string##substring}

Following syntax deletes the longest match of $substring from back of $string

${string%%substring}

Following sample shell script explains the above two longest substring match concepts.

$ cat longest.sh
#! /bin/bash filename="bash.string.txt" echo "After deletion of longest match from front:" ${filename##*.}
echo "After deletion of longest match from back:" ${filename%%.*} $ ./longest.sh
After deletion of longest match from front: txt
After deletion of longest match from back: bash

In the above example, ##*. strips longest match for ‘*.’ which matches “bash.string.” so after striping this, it prints the remaining txt. And %%.* strips the longest match for .* from back which matches “.string.txt”, after striping  it returns “bash”.

5. Find and Replace String Values inside Bash Shell Script

Replace only first match

${string/pattern/replacement}

It matches the pattern in the variable $string, and replace only the first match of the pattern with the replacement.

$ cat firstmatch.sh
#! /bin/bash filename="bash.string.txt" echo "After Replacement:" ${filename/str*./operations.} $ ./firstmatch.sh
After Replacement: bash.operations.txt

Replace all the matches

${string//pattern/replacement}

It replaces all the matches of pattern with replacement.

$ cat allmatch.sh
#! /bin/bash filename="Path of the bash is /bin/bash" echo "After Replacement:" ${filename//bash/sh} $ ./allmatch.sh
After Replacement: Path of the sh is /bin/sh

Taking about find and replace, refer to our earlier articles – sed substitute examples and Vim find and replace.

Replace beginning and end

${string/#pattern/replacement

Following syntax replaces with the replacement string, only when the pattern matches beginning of the $string.

${string/%pattern/replacement

Following syntax replaces with the replacement string, only when the pattern matches at the end of the given $string.

$ cat posmatch.sh
#! /bin/bash filename="/root/admin/monitoring/process.sh" echo "Replaced at the beginning:" ${filename/#\/root/\/tmp}
echo "Replaced at the end": ${filename/%.*/.ksh} $ ./posmatch.sh
Replaced at the beginning: /tmp/admin/monitoring/process.sh
Replaced at the end: /root/admin/monitoring/process.ksh

reference from:http://www.thegeekstuff.com/2010/07/bash-string-manipulation/

Bash String Manipulation Examples – Length, Substring, Find and Replace--reference的更多相关文章

  1. LeetCode : Given a string, find the length of the longest serial substring without repeating characters.

    Given a string, find the length of the longest serial substring without repeating characters. Exampl ...

  2. string manipulation in game development-C # in Unity -

    ◇ string manipulation in game development-C # in Unity - It is about the various string ● defined as ...

  3. Leetcode: Encode String with Shortest Length && G面经

    Given a non-empty string, encode the string such that its encoded length is the shortest. The encodi ...

  4. String Matching Content Length

    hihocoder #1059 :String Matching Content Length 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 We define the ...

  5. An universal algorithm design of fixed length substring locating

         An universal algorithm design of fixed length substring locating Stringlocating is a very commo ...

  6. CodeForces 159c String Manipulation 1.0

    String Manipulation 1.0 Time Limit: 3000ms Memory Limit: 262144KB This problem will be judged on Cod ...

  7. [LeetCode] Encode String with Shortest Length 最短长度编码字符串

    Given a non-empty string, encode the string such that its encoded length is the shortest. The encodi ...

  8. 05_整理String类的Length()、charAt()、 getChars()、replace()、 toUpperCase()、 toLowerCase()、trim()、toCharArray()使用说明

    Question: 整理String类的Length().charAt(). getChars().replace(). toUpperCase(). toLowerCase().trim().toC ...

  9. 数组有没有length()这个方法? String有没有length()这个方法?

    答:数组和string都没有Length()方法,只有Length属性.

随机推荐

  1. AfxBeginThread和AfxEndThread+内存泄露

    ref http://blog.csdn.net/kut00/article/details/4209680 启动线程: CWinThread* AfxBeginThread( 线程函数, this ...

  2. OSFM Tables

    OSFM - Oracle Shop Floor Management 1. (N) Shop Floor Manager > Lot Based Jobs (B: New) Status: U ...

  3. 转载:CEO应向软件工程师学习的7个技能

    软件工程师的哪些技能是值得CEO学习的?显然,软件工程师是逻辑的,高效的,注重细节的,有计划的,并且大多数CEO也是如此.但是,软件工程师还有一些更微妙,甚至是令人懊恼的品质,那么CEO是否可以从中学 ...

  4. POJ_3061_Subsequence_(尺取法)

    描述 http://poj.org/problem?id=3061 给定长度为n的数列整数以及整数S.求出总和不小于S的连续子序列的长度的最小值,如果解不存在输出0. Subsequence Time ...

  5. mac book air 装win7

    1. 使用mac book air A1465中 bootCamp制作启动U盘: 需要U盘一个8G,windows 7 原版镜像ISO安装文件一个,根据bootcamp操作提示选择文件及U盘, 注意U ...

  6. 处理MVC中默认的Json方法返回时间的问题

    利用 Json方法返回 数据时,如果有时间格式,会变成 "\/Date(1369419656217)\/" 这个样子,问了同事找到个解决方法 using Newtonsoft.Js ...

  7. MVC View基础

    View主要用于呈现数据.由于Controller和相关的Service已经处理完业务逻辑并将结果打包成model实体,View只需要怎么去获得model并将其转为Html 1选择需要渲染的视图 在上 ...

  8. struct ifconf和struct ifreq,获取网线插入状态

    这两天看用C获取当前网口的插入网线状态的程序,遇见了这两个不熟悉的结构体,看了头文件中的说明和详细. struct ifreq 这个结构定义在include/net/if.h,用来配置ip地址,激活接 ...

  9. chart控件怎么使x轴标签全部显示出来

    在vs2012中使用chart控件事,x轴的标签过多,致使默认只能显示其中的一部分,如图 当然,我们可以通过设置,使得x轴标签全部显示. 首先,通过chart控件属性,找到   “ChartAreas ...

  10. yarn环境的搭建

    1.首先,在zookeeper搭建成功,服务运行的基础上搭建yarn,其次,保证时间一致 2.在 /home/install/hadoop-2.5/etc/hadoop目录下配置一下几个配置文件: 第 ...