Skip to content

Variable Replacement and Truncate in Bash Command Line

homepage-banner

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.

Leave a message