Introduction
In this lab, you will learn about fundamental string operations in shell scripting. String operations are essential for manipulating and extracting data from text in various scripting tasks. You will explore concepts such as determining string length, finding character positions, extracting substrings, and replacing parts of strings. These skills are crucial for effective text processing in shell scripts.
Quick Reference Guide
Here's a quick overview of the string operations we'll cover in this lab:
Operation | Syntax | Description | Example |
---|---|---|---|
String Length | ${#string} |
Calculates the number of characters in a string | ${#"hello"} returns 5 |
Find Character Position | $(expr index "$string" "$char") |
Finds the position of a character in a string (1-indexed) | $(expr index "abcdef" "c") returns 3 |
Extract Substring | ${string:start:length} |
Extracts a portion of a string (0-indexed) | ${"hello":1:3} returns ell |
Replace First Occurrence | ${string/pattern/replacement} |
Replaces the first occurrence of a pattern | ${"hello"/l/L} returns heLlo |
Replace All Occurrences | ${string//pattern/replacement} |
Replaces all occurrences of a pattern | ${"hello"//l/L} returns heLLo |
Replace at Beginning | ${string/#pattern/replacement} |
Replaces pattern only if at beginning of string | ${"hello"/#he/HE} returns HEllo |
Replace at End | ${string/%pattern/replacement} |
Replaces pattern only if at end of string | ${"hello"/%lo/LO} returns helLO |