Bash string manipulation 2

abbazs

abbazs

Posted on July 7, 2024

Bash string manipulation 2

Bash string manipulation involves using parameter expansion to modify the value of a variable. Here are some common string manipulation techniques in bash:

Removing a substring from the front of a string

Remove shortest match of a pattern from the front

var="System Commands"
echo ${var#* }
Enter fullscreen mode Exit fullscreen mode

This removes the shortest match of * (anything followed by a space) from the beginning of the string, resulting in Commands.

Remove longest match of a pattern from the front

var="System Commands are useful"
echo ${var##* }
Enter fullscreen mode Exit fullscreen mode

This removes the longest match of * from the beginning of the string, resulting in useful.

Removing a substring from the end of a string

Remove shortest match of a pattern from the end

var="System Commands"
echo ${var% *}
Enter fullscreen mode Exit fullscreen mode

This removes the shortest match of * (space followed by anything) from the end of the string, resulting in System.

Remove longest match of a pattern from the end

var="System Commands are useful"
echo ${var%% *}
Enter fullscreen mode Exit fullscreen mode

This removes the longest match of * from the end of the string, resulting in System.

Extracting a substring

Extract substring from position

var="System Commands"
echo ${var:0:6}
Enter fullscreen mode Exit fullscreen mode

This extracts 6 characters starting from position 0, resulting in System.

Length of a string

var="System Commands"
echo ${#var}
Enter fullscreen mode Exit fullscreen mode

This returns the length of the string, which is 15.

Replacing part of a string

Replace first match

var="System Commands"
echo ${var/Commands/Operations}
Enter fullscreen mode Exit fullscreen mode

This replaces the first occurrence of Commands with Operations, resulting in System Operations.

Replace all matches

var="System Commands Commands"
echo ${var//Commands/Operations}
Enter fullscreen mode Exit fullscreen mode

This replaces all occurrences of Commands with Operations, resulting in System Operations Operations.

Example for extracting the first word using string manipulation

To extract the first word from a string, you can use:

var="System Commands"
echo ${var%% *}
Enter fullscreen mode Exit fullscreen mode

This removes everything from the first space to the end of the string, effectively extracting the first word, resulting in System.

These techniques allow you to manipulate strings in various ways directly within bash scripts, providing powerful tools for text processing without needing external utilities.

💖 💪 🙅 🚩
abbazs
abbazs

Posted on July 7, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Bash string manipulation 2
iitm Bash string manipulation 2

July 7, 2024