Introduction
You use substring extraction to get a part of a text stored in a variable. It helps you pick only the piece you need.
${variable:offset:length}text="Hello World" echo ${text:0:5}
text="Hello World" echo ${text:6}
text="Hello" echo ${text:10:3}
text="Hi" echo ${text:1:5}
#!/bin/bash full_text="2024-06-15_report.txt" # Extract year (first 4 characters) year=${full_text:0:4} # Extract month (characters 5 and 6) month=${full_text:5:2} # Extract day (characters 8 and 9) day=${full_text:8:2} # Extract file type (last 3 characters) file_type=${full_text: -3} # Print all extracted parts echo "Year: $year" echo "Month: $month" echo "Day: $day" echo "File type: $file_type"
${var:2:3} do in bash scripting?${var:offset:length} extracts a substring from var starting at offset with length characters.var starting at index 2 -> Option Atext?${var:offset:length}.filename="report2024.txt", what is the output of echo ${filename:6:4}?var="hello world"
echo ${var:5,3}${var:5,3} which is invalid and causes a syntax error.date="2024-06-15". Which command extracts the month part ("06") using substring extraction?${date:5:2} extracts "06" which is the month.Pass the test and this pattern moves unknown