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
24

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:15}
echo ${var:15:4}

$ ./substr.sh
geekstuff
geek

Also, refer to our earlier article to understand more about $*,
[email protected], $#, $$, $!, $?, $-, $_ 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

时间: 2025-01-31 04:05:21

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

Given a string, find the length of the longest substring without repeating characters.(给定一个字符串,找到最长的子串的长度,这个子串不存在重复的字符。 )

Given a string, find the length of the longest substring without repeating characters. Examples: Given "abcabcbb", the answer is "abc", which the length is 3. Given "bbbbb", the answer is "b", with the length of 1.

JDK6和JDK7中String类下的substring方法的代码对比(仅贴代码,未详述)

返回主页 回到顶端 jdk1.6版本String.java文件中关于substring的代码及描述 1 /** 2 * Returns a new string that is a substring of this string. The 3 * substring begins with the character at the specified index and 4 * extends to the end of this string. <p> 5 * Examples: 6 *

CodeForces 159c String Manipulation 1.0

String Manipulation 1.0 Time Limit: 3000ms Memory Limit: 262144KB This problem will be judged on CodeForces. Original ID: 159C64-bit integer IO format: %I64d      Java class name: (Any) One popular website developed an unusual username editing proced

An universal algorithm design of fixed length substring locating

     An universal algorithm design of fixed length substring locating Stringlocating is a very common operation not only in the SQL design but also in theclient development tools, in which functions are also supplied to realize thelocating operation,

Leetcode: Encode String with Shortest Length &amp;&amp; G面经

Given a non-empty string, encode the string such that its encoded length is the shortest. The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note: k will be a positive integ

string 中的 length函数 和size函数 返回值问题

string 中的 length函数 和 size函数 的返回值  (  还有 char [ ] 中 测量字符串的  strlen 函数 ) 应该是 unsigned int 类型的 不可以 和 -1 比较. 应尽量避免 unsigned int 类型 和 int类型 数据 的比较 .当unsigned int 类型 和 int类型 数据 比较 时 ,会 把int 类型 转换 为 unsigned int类型 .如果 int是负数 ,转换 为 unsigned int 会是 一个 很大 的正整数

python——unpack问题 ocr_recognize timeout , exception:unpack requires a string argument of length 46

rObjBuff = "".join(unpack('=%ds' % ObjLen, recv_buf[6+i*ObjLen:6+(i+1)*ObjLen]))score, bbox1, bbox2, bbox3, bbox4, p00, p01, p10, p11, p20, p21, p30, p31, p40, p41 = unpack('=5f10H', rObjBuff) 错误示例: rObjBuff = unpack('=%ds' % ObjLen, recv_buf[6+

VK Cup 2012 Qualification Round 2 C. String Manipulation 1.0 字符串模拟

C. String Manipulation 1.0 Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 codeforces.com/problemset/problem/91/B Description One popular website developed an unusual username editing procedure. One can change the username only by deleting some characte

JavaSE7基础 得到一个正整数有几位 String.valueOf(num).length()

版本参数:jdk-7u72-windows-i586注意事项:博文内容仅供参考,不可用于其他用途. 代码 class Demo{ public static void main(String[] args){ int num = 1234; int n = String.valueOf(num).length(); System.out.println(num+":"+n+"位数"); } } 编译与运行 ------------------------------