Wildcard characters in Shell Script Linux
In shell scripting, wildcard characters are used to match multiple characters in a string. They can be used for filename expansion and pattern matching.
There are two main wildcard characters in shell scripting:
- (asterisk): Matches zero or more characters in a string. For example, if you have files named file1, file2, file3, and you want to list all the files in a directory, you can use the command
ls file*
to list all the files that start with “file”. - ? (question mark): Matches exactly one character in a string. For example, if you have files named file1, file2, and you want to list just file1, you can use the command
ls file?
to list just the file named file1.
In addition to the above two wildcard characters, there are a few other wildcard characters that you can use in shell scripting:
- (square brackets): Matches any one of the characters in the brackets. For example, if you have files named file1, file2, and file3, and you want to list all the files that start with “file” and end with 1 or 2, you can use the command
ls file[12]
to list just the files named file1 and file2. - [! ] (exclamation mark): Matches any character not in the brackets. For example, if you have files named file1, file2, and file3, and you want to list all the files that start with “file” and end with any character except 1 or 2, you can use the command
ls file[!12]
to list just the file named file3.
Here are some examples of how to use wildcard characters in shell scripting:
- List all files in the current directory:
ls *
2. List all text files in the current directory:
ls *.txt
3. List all files that start with the letter ‘f’:
ls f*
4. List all files that have a single character before the .txt extension:
ls file?.txt
5. List all files that have a two-letter extension:
ls *.??
6. Match all files that start with a and have exactly three characters:
ls a???
7. Match all files that start with a, b or c and have exactly three characters:
ls [abc]???
8. Match all files that start with a, b or c and have exactly three characters, but exclude files that start with b:
ls [a!b]???
In addition to these basic wildcard characters, shell scripting also supports extended globbing patterns, which provide more advanced wildcard matching capabilities. These patterns can be used to match files based on various criteria such as size, modification time, and permissions.
For example, the following command can be used to match all files that are larger than 100 kilobytes:
find . -type f -size +100k
In this example, the -type f
option is used to match only files, while the -size +100k
option is used to match files that are larger than 100 kilobytes.
Overall, wildcard characters are a powerful tool in shell scripting, and can greatly simplify the process of matching and manipulating files in Linux.