Simple usage of Linux shell ${}

Reprinted from: http://www.cnblogs.com/xudong-bupt/p/3567096.html

 

 For the sake of completeness, I will use some examples to illustrate some of the special functions of ${ }:

Suppose we define a variable as:
file=/dir1/dir2/dir3/my.file.txt,
we can replace it with ${ } to get different values:
${file#*/}: remove the first / and The string to the left: dir1/dir2/dir3/my.file.txt
${file##*/}: remove the last / and the string to the left: my.file.txt
${file#*.} : remove the first . and the string to the left: file.txt
${file##*.}: remove the last . and the string to the left: txt
${file%/*}: remove the last / and the string to its right: /dir1/dir2/dir3
${file%%/*}: remove the first / and its right: (null)
${file%.*}: take Remove the last . and the string to the right: /dir1/dir2/dir3/my.file
${file%%.*}: Remove the first . and the string to the right: /dir1/dir2/dir3/ my

 

The way to remember is:

# is to remove the left side (on the disc, # is to the left of $)

% is to remove the right (% is to the right of $ on the disc)

A single symbol is the smallest match; two symbols is the largest match.

 

${file:0:5}: extract the leftmost 5 bytes: /dir1
${file:5:5}: extract the 5 consecutive bytes to the right of the 5th byte: /dir2
We can also Replace the string in the value:
${file/dir/path}: replace the first dir with path: /path1/dir2/dir3/my.file.txt
${file//dir/path}: replace All dirs are replaced with path: /path1/path2/path3/my

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326415265&siteId=291194637