Crmgo Blog

Working with strings in bash

Working with strings in bash

Extracting a substring ${string:position} — from position to the end ${string:position:length} — from position, length characters long ${string: -length} — the last length characters Removing part of a string ${string#substring} — up to the first occurrence from the beginning ${string##substring} — up to the last occurrence from the beginning ${string%substring} — up to the first occurrence from the end…

Working with strings in bash

 

Extracting a substring

${string:position} — from position to the end

${string:position:length} — length characters starting from position

${string: -length} — the last length characters

Removing part of a string

${string#substring} — up to the first match from the beginning

${string##substring} — up to the last match from the beginning

${string%substring} — up to the first match from the end

${string%%substring} — up to the last match from the end

Replacing a substring

${string/substring/replacement} — first occurrence

${string//substring/replacement} — all occurrences

${var/#Pattern/Replacement} — If the variable var contains a match for Pattern, and the matching substring is at the beginning of the string (prefix), it is replaced with Replacement. The search starts from the beginning of the string.

${var/%Pattern/Replacement} — If the variable var contains a match for Pattern, and the matching substring is at the end of the string (suffix), it is replaced with Replacement. The search starts from the end of the string.

Note: This post may be AI-assisted and then human-edited. Editorial responsibility: Dmytro Lomaka, Kaltenkirchen.