RootConsole.net

advices, tips, blog

  • Home

String manipulation in Bash

Posted by Admin on October 17, 2013
Posted in: Bash, Programming. Tagged: bash, string.

Bash has ability of simple string manipulation. It has a various operators which allow do some basic text operations. This short article shows how to use these features in action with Bash.

Let’s say we have a variable text:

$ text="This is a sample text."

String length

We can get string length using a following syntax.

${#text}

We can simply display it.

$ echo ${#text}

Getting a substring

There are three versions of this operator (some arguments are optional).

1. Getting a substring starting on nth char:

${text:n}

Using text from our example:

$ n=3
$ echo ${text:n}
s is a sample text.

2. Getting a substring with specified length:

${text:n:len}

where len is a length of the substring. For example:

$ len=7
$ n=3
$ echo ${text:n:len}
s is a

3. Getting substring starting at beginning of the $text variable. Value of the second argument is zero.

$ len=3
$ echo ${text::len}
Thi

Substring match

1. How to check regexp match? Matching word ‘sample’ inside $text string. Returned value is a number of matched characters.

$ expr match "$text" "^.*sample.*$"
22

2. This expression returns index in $text string where any of ‘abc’ characters is found.

$ expr index "$text" "abc"
9

In this example first found letter is ‘a’ (the 9th).

Posts navigation

← Postgrey daemon doesn’t start
How to split a file into several parts? →
  • or
    BTC
    1BLAWYYBP9ZGUwsJigtqW7JWLoaFFfZhMp
  • Contact

Proudly powered by WordPress Theme: Parament by Automattic.