STRINGS
We’ve seen earlier that bash STRINGS are groups of characters.
Can we manipulate these strings inside bash
scripts?
Parameter substitution for strings
Earlier we learned that surrounding a variable
with ${}
indicates you want to treat it as a parameter
and access more information about the variable.
Here are some additional parameter substitutions to help you strings:
${#string}
: length of string.prompt> a="apple" prompt> echo ${#a} ${a} 5 apple
${string:position:length}
: substring starting atposition
forlength
characters.prompt> file=1j6z.pdb prompt> echo ${file:0:4} 1j6z prompt> echo ${file:(-3):2} pd
- expr index string substring : returns position at which
substring
startsprompt> file=1j6z.pdb prompt> ix=$(expr index $file ".pdb") prompt> echo ${file:$((--ix))} .pdb prompt> echo ${file:0:$ix} 16jz
${string/substring/replacement}
: substitutesubstring
forreplacement
for/ = first
or// = all
occurrences of substring.prompt> file=fp_math.sh prompt> echo ${file/h/#} fp_mat#.sh prompt> echo ${file//h/#} fp_mat#.s# prompt> echo ${file//h/} fp_mat.s
Expression Meaning ${#string} Length of $string ${string:position} Extract substring from $string at $position ${string:position:length} Extract $length characters substring from $string at $position ${string#substring} Strip shortest match of $substring from front of $string ${string##substring} Strip longest match of $substring from front of $string ${string%substring} Strip shortest match of $substring from back of $string ${string%%substring} Strip longest match of $substring from back of $string ${string/substring/replacement} Replace first match of $substring with $replacement ${string//substring/replacement} Replace all matches of $substring with $replacement ${string/#substring/replacement} If $substring matches front end of $string, substitute $replacement for $substring ${string/%substring/replacement} If $substring matches back end of $string, substitute $replacement for $substring expr match “$string” ‘$substring’ Length of matching $substring* at beginning of $string expr index “$string” $substring Numerical position in $string of first character in $substring that matches EXERCISE: given a filename and an extension create a script that adds “_old” before the extension.
prompt> vi cp_old.sh #!/bin/bash file=$1 ext=$2 ix=$(expr index $file $2) base=${file:0:$((--ix))} cp ${file} "${base}_old${ext}" prompt> touch 1j6z.pdb prompt> ls 1j6z* 0 1j6z.pdb prompt> ./cp_old.sh 1j6z.pdb .pdb prompt> ls 1j6z* 0 1j6z_old.pdb 0 1j6z.pdb
Prev ARITHMETIC | Next Arguments | UP : BASH scripting | Top : Course Overview © 2017 Texas Advanced Computing Center