Usage of $ {}, ## and %% in Shell

The method of memorizing is:
# is to remove the left (# on the keyboard # on the left of $)
% is to remove the right (% on the keyboard to the right of $)
a single symbol is the smallest match; two symbols are the largest match

 

Suppose we defined a variable as: file = / dir1 / dir2 / dir3 / my.file.txt

You can substitute $ {} to get different values:

 

$ {file # * /}: Delete the first / and the string to its left: dir1 / dir2 / dir3 / my.file.txt

$ {file ## * /}: Delete the last / and the string to the left: my.file.txt

 

$ {file% / *}: delete the last / and the string to the right: / dir1 / dir2 / dir3

$ {file %% / *}: delete the first / and the string to the right: (empty value)

 

$ {file: 0: 5}: extract the left 5 bytes: / dir1

$ {file: 5: 5}: extract 5 consecutive bytes to the right of the 5th byte: / dir2

 

$ {file / dir / path}: Replace the first dir with path: /path1/dir2/dir3/my.file.txt

$ {file // dir / path}: Replace all dir with path: /path1/path2/path3/my.file.txt

 

$ {# var} can calculate the length of the variable value:

$ {# file} gets 27 because /dir1/dir2/dir3/my.file.txt is 27 bytes

Guess you like

Origin www.cnblogs.com/Linux-guowen/p/12713425.html