Introduction
This helps you quickly remove a part from the start of a text stored in a variable. It is useful when you want to clean or shorten text without changing the original.
${variable#pattern}filename="/home/user/file.txt" basename=${filename#"/home/user/"} echo "$basename"
url="https://example.com/page" clean_url=${url#"https://"} echo "$clean_url"
text="abc123abc" result=${text#abc} echo "$result"
#!/bin/bash full_path="/var/log/syslog" # Remove the directory path, keep only the file name file_name=${full_path#"/var/log/"} echo "Full path: $full_path" echo "File name only: $file_name"
${var#pattern} do?${var#pattern} is used in Bash to remove a prefix pattern from the start of the variable's value.abc from variable var in Bash?${var#abc}.var="folder/subfolder/file.txt", what is the output of echo ${var#*/}?*/*/ matches the shortest prefix ending with a slash.*/*/ is "folder/". Removing it leaves "subfolder/file.txt".var="abc123abc456"
echo ${var##abc*}
It outputs an empty line. Why?abc*abc* matches 'abc' followed by zero or more any characters.abc* matches the longest prefix, so nothing remains -> Option Cpath="folder/home/user/docs/report.txt". Which command removes only the first slash and everything before it, leaving home/user/docs/report.txt?path is "folder/home/user/docs/report.txt".${path#/*} removes shortest prefix matching slash followed by anything, but path doesn't start with /, so no match.${path##/*} removes longest prefix matching slash-anything, no match.${path##*/} removes longest prefix up to last slash, leaving only filename "report.txt".${path#*/} removes shortest prefix up to first slash ("folder/"), leaving "home/user/docs/report.txt".${path#*/}.Pass the test and this pattern moves unknown