Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a fixed prefix/suffix from a string in Bash

Tags:

bash

In my bash script I have a string and its prefix/suffix. I need to remove the prefix/suffix from the original string.

For example, let's say I have the following values:

string="hello-world" prefix="hell" suffix="ld" 

How do I get to the following result?

result="o-wor" 
like image 918
Dušan Rychnovský Avatar asked May 18 '13 11:05

Dušan Rychnovský


People also ask

How do I remove something from a string in bash?

Remove Character from String Using cut Cut is a command-line tool commonly used to extract a portion of text from a string or file and print the result to a standard output. You can also use this command for removing characters from a string.

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script.


1 Answers

$ foo=${string#"$prefix"} $ foo=${foo%"$suffix"} $ echo "${foo}" o-wor 

This is documented in the Shell Parameter Expansion section of the manual:

${parameter#word}
${parameter##word}

The word is expanded to produce a pattern and matched according to the rules described below (see Pattern Matching). If the pattern matches the beginning of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the # case) or the longest matching pattern (the ## case) deleted. […]

${parameter%word}
${parameter%%word}

The word is expanded to produce a pattern and matched according to the rules described below (see Pattern Matching). If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern (the % case) or the longest matching pattern (the %% case) deleted. […]

like image 152
Adrian Frühwirth Avatar answered Oct 16 '22 23:10

Adrian Frühwirth