Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to extract a substring in bash

Tags:

linux

bash

shell

I have the following string in bash with length > 4

str = "abcdefghijklmno" 

and I want to extract into str2 the 5 first charachter of str. So

str2="abcde" 

How to do it with bash?

like image 512
MOHAMED Avatar asked May 10 '13 14:05

MOHAMED


People also ask

How do you substring a string in Unix?

Unix shells do not traditionally have regex support built-in. Bash and Zsh both do, so if you use the =~ operator to compare a string to a regex, then: You can get the substrings from the $BASH_REMATCH array in bash.

How do you find the substring of a string in a shell?

Using Regex Operator Another option to determine whether a specified substring occurs within a string is to use the regex operator =~ . When this operator is used, the right string is considered as a regular expression. The period followed by an asterisk .


1 Answers

Do use the expression

{string:position:length} 

So in this case:

$ str="abcdefghijklm" $ echo "${str:0:5}" abcde 

See other usages:

$ echo "${str:0}"      # default: start from the 0th position abcdefghijklm $ echo "${str:1:5}"    # start from the 1th and get 5 characters bcdef $ echo "${str:10:1}"   # start from 10th just one character k $ echo "${str:5}"      # start from 5th until the end fghijklm 

Taken from:
- wooledge.org - How can I use parameter expansion? How can I get substrings? How can I get a file without its extension, or get just a file's extension?
- Shell Command Language - 2.6.2 Parameter Expansion

like image 60
fedorqui 'SO stop harming' Avatar answered Sep 28 '22 03:09

fedorqui 'SO stop harming'