In the shell programming process, you often encounter problems getting file names and file suffix names. The general processing methods are as follows:
#code
file= "Thisfile.txt"
echo "filename:${file%.*}"
echo "extension:${file##*.}
" #result
filename:thisfile
extension:txt
It mainly utilizes a series of string manipulation symbols built into the shell. The specific operational symbols are described below:
An expression |
meaning |
${#string} |
$string length |
${string:position} |
in $string , extract the substring from the location $position |
${string:position:length} |
in $string, starting from position $position to extract the length of $length Substring |
${string#substring} |
Remove the substring of the shortest matching $substring |
${string# #substring} |
deletes the substring of the longest matching $substring from the beginning of the variable $string |
${string%substring} |
deletes the shortest matching $substring substring from the end of the variable $string |
${string%%substring} |
deletes the substring of the longest matching $substring from the end of the variable $string |
${string/old/new} |
uses $new to replace the first matching $old |
${string//old/new} |
uses $new to replace all matching $old |
The
${string/#old/new} |
replaces the beginning. If $string begins with $old, replace the end with $new with the |
${string/%old/new} |
. If $string ends with $old, replace the |
with $new
Note: You cannot use regular expressions, you can only use the shell extensions of? *. Example
Separate directories for the environment variable path, one for each row.
Echo-e ${path//:/' \ n '}
Replace All ":" in $path with "\ n" and output through ECHO-E.
The-e parameter of ECHO, which specifically handles some characters, and "\ n" is exported as a character without-E.
Path string processing.
DirName ${fullpath} |
Take a directory section |
BaseName ${fullpath} |
Take file name part |
basename FullPath {fullpath} {EXT} |
Takes the filename part and removes the specified extension |
#!/bin/sh
fullname= "/home/dwdxdy/opencv-2.3.0.tar.bz2"
ext= ". bz2" DirName
${fullname}
basename $ {FULLNAME}
BaseName ${fullname} ${ext} echo
${fullname%/*} echo ${fullname##*/
} echo
${fullname##*.}
Using the shell's built-in string processing, you can complete the Dirname,basename function.
In addition, in the shell can also invoke other commands to do string operations, such as: awk,sed and so on.
Using internal operators instead of awk,sed and other external programs, you can omit the time to start the external program, speeding up the operation of the entire shell program.
In general, the first choice of shell internal operators, if the internal operators can not complete the corresponding functions, and then consider awk,sed and other external programs.