bash string manipulation

These quick string manipulations might save you some time. This works with bash starting from version 4.0

Function

Input String s

Bash

Output String

Show ABC123abc123 ${s} ABC123abc123
Show UPPERCASE ABC123abc123 ${s^^} ABC123ABC123
Show lowercase ABC123abc123 ${s,,} abc123abc123
Show length ABC123abc123 ${#s} 12
Show last 4 characters ABC123abc123 ${s: -4} c123
Show first 4 characters
ABC123abc123 ${s:0:4} ABC1
Show characters 4 to 10 ABC123abc123 ${s:3:6} 123abc
Remove first 7 characters
ABC123abc123 ${s:7} bc123
Remove last 4 characters
ABC123abc123 ${s::-4} ABC123ab
Remove first 2 and final 3 characters ABC123abc123 ${s:2:-3} C123abc
Remove substring A*12 in front ungreedy ABC123abc123 ${s#A*12} 3abc123
Remove substring A*12 in front greedy ABC123abc123 ${s##A*12} 3
Remove substring 123* at end ungreedy ABC123abc123 ${s%123*} ABC123abc
Remove substring 123* at the end greedy ABC123abc123 ${s%%123*} ABC
Remove 1 time substring 123 ABC123abc123 ${s/123} ABCabc123
Remove all substrings 123 ABC123abc123 ${s//123} ABCabc
Remove all letters ABC123abc123 ${s//[a-z]} 123123
Replace 1 time 123 by abc ABC123abc123 ${s/123/abc} ABCabcabc123
Replace everywhere 123 by abc ABC123abc123 ${s//123/abc} ABCabcabcabc
Replace beginning ABC by 123 ABC123abc123 ${s/#ABC/123} 123123abc123
Replace ending 123 by abc ABC123abc123 ${s/%123/abc} ABC123abcabc
This entry was posted in bash, linux, macosx and tagged , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *