Bash String Manipulation Examples – Length, Substring, Find and Replace--reference
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的更多相关文章
- 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 ...
- string manipulation in game development-C # in Unity -
◇ string manipulation in game development-C # in Unity - It is about the various string ● defined as ...
- 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 ...
- String Matching Content Length
hihocoder #1059 :String Matching Content Length 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 We define the ...
- An universal algorithm design of fixed length substring locating
An universal algorithm design of fixed length substring locating Stringlocating is a very commo ...
- CodeForces 159c String Manipulation 1.0
String Manipulation 1.0 Time Limit: 3000ms Memory Limit: 262144KB This problem will be judged on Cod ...
- [LeetCode] Encode String with Shortest Length 最短长度编码字符串
Given a non-empty string, encode the string such that its encoded length is the shortest. The encodi ...
- 05_整理String类的Length()、charAt()、 getChars()、replace()、 toUpperCase()、 toLowerCase()、trim()、toCharArray()使用说明
Question: 整理String类的Length().charAt(). getChars().replace(). toUpperCase(). toLowerCase().trim().toC ...
- 数组有没有length()这个方法? String有没有length()这个方法?
答:数组和string都没有Length()方法,只有Length属性.
随机推荐
- android & Linux uevent机制
Linux uevent机制 Uevent是内核通知android有状态变化的一种方法,比如USB线插入.拔出,电池电量变化等等.其本质是内核发送(可以通过socket)一个字符串,应用层(andro ...
- JS中String,Math常用函数
String对象: 1.length属性 说明:获取字符串的长度 实例: var str="abc"; var i=str.length;//output:3 2.charAt() ...
- web移动开发最佳实践之html篇
一.前言 在目前的移动应用开发大潮下,使用web技术进行移动应用开发正变得越来越流行,它主要使用html5.css3.js等技术,在跨平台性.可移植性方面具有无可比拟的优势,特别适合开发对性能要求不太 ...
- spring log4j.properties
log4j.properties log4j.rootLogger=info,appender2,appender3 #appender2\u914D\u7F6E FileAppender log4j ...
- REST Web 服务介绍
在项目上使用到了Rest技术,应该是Rest的服务概念才对.主要是对外(BPM)暴露API来提供Service.推荐一篇有质量的文章,接下来会系统一点的学习一下Restful概念.http://kb. ...
- 不要浪费人生的每一天 ——Dropbox创始人在麻省理工的演讲 z
Dropbox 创始人,CEO 德鲁·休斯顿(Drew Houston)近期在美国麻省理工学院的毕业典礼上发表演讲.他向大学生提出了 3 点人生建议:追逐自己感兴趣的事,找到最合适的圈子,以及不要浪费 ...
- [liu yanling]测试流程
测试流程 1.制定测试计划 2.编辑测试用例 3.执行测试用例 4.发现并提交BUG 5.开发组修正BUG 6.对已修正BUG进行返测 7.修正完成的BUG将状态置为已关闭,未正确修正的BUG重新激活
- Scala学习笔记(一)数据类型
.类型参数化数组 val arrayString = Array[String](2); arrayString (0)="Hello"; arrayString (1)=&quo ...
- HW5.19
public class MyTriangle { public static boolean isValid(double side1, double side2, double side3) { ...
- 坑爹的IE quirk模式【转】
调试一个页面,ie下面页面css样式很是奇怪,各种失效.找了半天原因不知道怎么回事.最后在调试工具中发现,文档模式为quirk,改成别的(IE 7|8|9)正常. 为什么会自动选择此文档模式呢? 先看 ...