replace last n characters of a string in shell script

Initial string: inventory_1515.txt
Replaced string: inventory_2121.csv

Using sed with regex
echo 'inventory_1515.txt' | sed 's/[0-9]\{4\}\.txt$/2121.csv/'

Using sed with exact string replace
echo 'inventory_1515.txt' | sed 's/1515.txt/2121.csv/'

Using string slice,remove the last n characters and then concatenate with a new string.

A='inventory_1515.txt'
B=${A:0:${#A}-8}
C="$B""2121.csv"
echo $C

Search within Codexpedia

Custom Search

Search the entire web

Custom Search