Search This Blog

Shell scripting: extract substring (or path components) from string in BASH

str="I like shell scripting."

echo ${str:7:5} # 7 is offset, 5 is length, it will print shell

root=/a
path=/a/b/c
echo ${path#*/}     # trim the prefix: a/b/c
echo ${path#/a/}    # trim the prefix: b/c
echo ${path#$root/} # trim the prefix: b/c
echo ${path#*b}     # trim the prefix: /c

name=/a/b/c.txt
echo ${name%/*}   # trim the suffix: /a/b
echo ${name%.txt} # trim the suffix: /a/b/c






see also

No comments:

Post a Comment