Saturday, May 3, 2014

Bash Specialities, part 3

This part shows examples for bash string manipulation: string matching and replacing, some substring operations and positional parameters operations.

String matching:
s="abcABC123ABCabc"

# string length
echo ${#s}

# match from the beginning
echo ${s##a*C} # matches longest string (acbABC123ABC)
echo ${s#a*C} # matches shortest string (acbABC)

# match from the end
echo ${s%%B*c} # matches longest string (BC123ABCabc)
echo ${s%B*c} # matches shortest string (BCabc)
String replacing:
# some string replacing examples
echo -e "\nString replacing"

s="abcABC123ABCabc"

# replace first match
echo ${s/ABC/000} # (abc000123ABCabc)
# replace all matches
echo ${s//ABC/000} # (abc000123000abc)

# replace first match with empty string
echo ${s/ABC} # (abc123ABCabc)
# replace all matches with empty string
echo ${s//ABC} # (abc123abc)

# replace if string matches from beginning
echo ${s/#abc/000} # (000ABC123ABCabc)
# replace if string matches from end
echo ${s/%abc/000} # (abcABC123ABC000)
Substring manipulation:
# some substring examples
echo -e "\nSUBString operations"

s="abcABC123ABCabc"

# remove first n chars from string
echo ${s:0} # (abcABC123ABCabc)
echo ${s:1} # (bcABC123ABCabc)
echo ${s:5} # (C123ABCabc)

# remove last n chars from string (indexing from the right end)
echo ${s: -4} # (Cabc)
echo ${s:(-4)} # (Cabc)

# print n chars from substring
echo ${s:4:6} # (BC123A)
# print n chars from substring (indexing from right)
echo ${s: -7:5} # (3ABCa)
echo ${s:(-7):5} # (3ABCa)
Positional parameters operations:
echo -e "\nPositional parameters"

# print all
echo ${*}
echo ${@}
# print count
echo ${#*}
echo ${#@}

# print from 3rd param (including 3rd)
echo ${*:3}
echo ${@:3}
# print 2 params, beginning from 3rd (including 3rd)
echo ${*:3:2}
echo ${@:3:2}

No comments:

Post a Comment