Variable Replacement and Truncate in Bash Command Line
Introduction
Bash is a powerful command-line shell that can be used to execute complex commands and scripts. It provides a wide range of tools and features that can make your life easier when working with the command line.
Variable replacement is a feature in Bash that allows you to replace a substring in a variable with another substring. There are several ways to do variable replacement in Bash. One of the most common ways is to use the ${variable/pattern/replacement} syntax. In this syntax, the pattern is the substring you want to replace, the replacement is the substring you want to replace the pattern with, and the variable is the variable containing the substring.
Match & Delete
Left -> Right
1. Delete by matching from front to back at one time
VAR=hahaha
echo ${VAR#*h}
# ahaha
2. Greedy mode, delete by matching from front to back
VAR=hahaha
echo ${VAR##*h}
# a
Right -> Left
1. Delete by matching from back to front at one time
VAR=hahaha
echo ${VAR%a*}
# hahah
2. Greedy mode, delete by matching from back to front
VAR=hahaha
echo ${VAR%%a*}
# h
About %
and #
#
removes from the left (on the keyboard,#
is to the left of%
)%
removes from the right (on the keyboard,%
is to the right of#
)- The symbol used once is the minimum match, and two consecutive symbols are the maximum match
Match & Replace
Replace once
VAR=hahaha
echo ${VAR/a/A}
# hAhaha
Greedy mode, replace all
VAR=hahaha
echo ${VAR//a/A}
# hAhAhA
Truncate
VAR=hahaha
echo ${VAR:0:5} #Extract the first 1-5 bytes
# hahah
echo ${VAR:3:2} #Extract 2 consecutive bytes to the right of the third byte
# ah
Variable replacement and truncate are powerful features in Bash that allow you to manipulate strings in various ways. By using these features, you can automate tasks, manage files, and perform complex data processing. In this blog post, we have discussed the summary of variable replacement and truncate in Bash. I hope you find this information helpful in your Bash scripting journey.
Small world. Big idea!
- Welcome to visit the knowledge base of SRE and DevOps!
- License under CC BY-NC 4.0
- No personal information is collected
- Made with Material for MkDocs and generative AI tools
- Copyright issue feedback me#imzye.com, replace # with @
- Get latest SRE news and discuss on Discord Channel