Slicing Strings
Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 16 of 39.
Bash can measure and cut the text in a variable without another program. ${#s} is the length of s. ${s:start:length} takes a slice: start counts from 0, and length is how many characters to keep.
day="Wednesday"
echo "${#day}" # 9
echo "${day:0:3}" # Wed
echo "${day:3:3}" # nes
echo "${day: -3}" # dayA negative start counts from the end, and a slice without a length runs to the end. Keep the space before the minus: ${day:-3} is a different expansion and prints Wednesday.
echo "${day^^}" # WEDNESDAY
echo "${day,,}" # wednesday^^ turns every letter to uppercase and ,, to lowercase. None of these change the variable itself. Store a result to work on it further: low=${day,,}, then ${low:0:3} is wed.
Challenge
EasyWrite a script that makes a name badge from a surname.
- Open
badge.sh. Its first argument is a surname. - Print
Badge:followed by the surname in uppercase. - Print
Letters:followed by the length of the surname. - Print
Code:followed by the first three letters, a-, and the last two letters, all in lowercase. - Save the file.
Try it: run bash badge.sh Johnson. It prints:
Badge: JOHNSON
Letters: 7
Code: joh-onThen run bash badge.sh DeLuca, which mixes cases:
Badge: DELUCA
Letters: 6
Code: del-caTry it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Bash Scripting
1Arguments And Exit Codes
Script ArgumentsAll The ArgumentsExit CodesChecking ArgumentsRecap - Unit Converter4Strings And Arrays
Slicing StringsTrimming And ReplacingDefault ValuesArraysReading Files Line By LineRecap - CSV ReportPractice on your own: Terminal playground