During shell programming, you often encounter the problem of getting the file name and file suffix. The general solution is as follows:
1 # Code 2 file = " thisfile.txt " 3 echo " filename :$ {file %. *} " 4 echo " extension :$ {file ##*.} " 5 # result 6 filename: thisfile 7 Extension: TXT
It mainly utilizes a series of character string operation symbols built in shell. The specific operation symbols are described as follows:
Expression |
Description |
$ {# String} |
$ String Length |
|
|
$ {String: Position} |
In $ string, the substring is extracted from position $ position. |
$ {String: Position: length} |
In $ string, the Child string with the length of $ length is extracted from the position $ position. |
|
|
$ {String # substring} |
From the beginning of the variable $ string, delete the substring that matches the minimum $ substring. |
$ {String ## substring} |
Removes the substring that matches $ substring at the beginning of the variable $ string. |
$ {String % substring} |
Removes the substring that matches the minimum value of $ substring from the end of the variable $ string. |
$ {String % substring} |
Removes the substrings that match the longest $ substring from the end of the variable $ string. |
|
|
$ {String/old/new} |
Use $ new to replace the first matched $ old |
$ {String // old/new} |
Use $ new to replace all matched $ old |
$ {String/# old/new} |
If $ string starts with $ old, replace it with $ new. |
$ {String/% old/new} |
End of replacement. If $ string ends with $ old, replace it with $ new. |
|
|
Note: you cannot use regular expressions. You can only use regular expressions? * Shell extension.
Some examples are described as follows:
Separate the directories of the Environment Variable path and display one directory in each line.
1 Echo-E $ {path//:/'\ N '}
Replace all ":" In $ path with "\ n" and output it through ECHO-e.
The-e parameter of ECHO, especially for some characters. If there is no-e, "\ n" is output as a character.
Path string processing.
Dirname $ {fullpath}
Basename $ {fullpath}
Basename $ {fullpath }$ {ext} takes the file name and removes the specified extension.
1 #! /Bin/ Sh 2 3 Fullname =" /Home/dwdxdy/OpenCV-2.3.0.tar.bz2 " 4 EXT = " . Bz2 " 5 Dirname $ {Fullname} 6 Basename $ {Fullname} 7 Basename $ {Fullname }$ {ext} 8 9 Echo $ {Fullname % /* } 10 Echo $ {fullname ## */ } 11 Echo $ {Fullname ##*.}
You can use the built-in shell string processing to complete the dirname and basename functions.
In addition, you can also use other commands in shell to perform various string operations, such as awk and sed.
Use internal operators instead of external operators such as awk and SEDProgramTo speed up the running of the entire shell program..
Generally, the shell internal operator is preferred. If the internal operator cannot complete the corresponding functions, consider external programs such as awk and sed.