Transform text with sed and awk
sed applies editing commands to a stream; s/old/new/ replaces the first match per line by default, and g replaces all nonoverlapping matches. It writes transformed text to stdout unless told otherwise. awk is a separate programming language for record and field processing: -F selects an input field separator, $1 and $2 are fields, and END executes after input. Single-quote fixed programs so Bash does not expand their $ variables. Pass data to awk using -v rather than building program text from input; values with backslash escapes need additional care. sed replacement text has its own metacharacters such as &. Avoid interpolating arbitrary data into a sed program or editing real files in place during practice. The -v option separates the value from program source, but awk may interpret backslash escapes in the value. The total example assumes validated numeric fields: awk numeric coercion is not input validation.
Practical examples
Run each example as a separate script in a fresh noninteractive Bash 5.2 process and empty practice directory. Tests use C locale; do not enter expected output as code.
Substitute a fixed label
Expected stdout:
final finalThe g flag replaces both matches; input is not modified.
Aggregate fields
printf '%s\n' 'apple:3' 'pear:4' 'apple:2' | awk -F ':' '{ total += $2 } END { print total+0 }'Expected stdout:
9The awk program adds field two of each record. total+0 also prints zero for empty input.
Pass a fixed search value
target='daily report'printf '%s\n' 'daily report:3' 'weekly report:5' | awk -F ':' -v wanted="$target" '$1 == wanted { print $2 }'Expected stdout:
3The value is an argument, not inserted into the awk program. This example uses simple text without escapes.
Common mistakes
Do not put awk field expressions in Bash double quotes, or assume sed -i is portable. For quoted CSV or complex formats use a parser that understands the format.
Practice
Create item:quantity records with small integer quantities. Use sed to normalize a fixed label and awk to total quantities; add one more record and verify the new total.
Next: Archives, checksums and temporary files