Bash String Manipulation
This page answers questions like these:
- How to get the first N chars of a string?
- How to get the last N chars of a string?
- How to get the middle N chars of a string?
- How to get a substring of a string?
Related Links:
Embed Quotes in a Shell Command or String
Shell String Containing Spaces is Not Splitting
Shell (Bash/Bourne/Korn) Alias Taking Multiple Arguments
First N Characters of a String:
$ STR="123456789"
$ echo "${STR::3}" # Print the first 3 characters of string STR.
123
All but the First N Characters of a String:
$ STR="123456789"
$ echo "${STR:3}" # Print all but the first 3 characters of string STR.
456789
Last N Characters of a String:
$ STR="123456789"
$ echo "${STR: -3}" # Print the last 3 characters of string STR.
789
- N.B. A space before the minus is required!
All but the Last N Characters of a String:
$ STR="123456789"
$ echo "${STR::-3}" # Print all but the last 3 characters of string STR.
123456
Middle N Characters of a String:
$ STR="123456789"
$ echo "${STR:2:3}" # Print 3 characters, starting from the character at index 2.
345
- N.B. Characters are indexed/numbered starting from zero! So, the first character of a string is at index 0.
Related Links:
Embed Quotes in a Shell Command or String
Shell String Containing Spaces is Not Splitting
Shell (Bash/Bourne/Korn) Alias Taking Multiple Arguments
Home > Linux / Unix > Bash String Manipulation
Tags: first N chars of string, last N chars of string, all but the first N chars of a string, all but last N chars of a string, substring, string manipulation, shell, command, string, linux, unix, solaris, bsd, aix
Copyright © HelpDoco.com
shell-string-manipulation.txt
Linux-Unix/bash-string-manipulation.htm
5