Globbing और Wildcards
In this page:
*.txt # any characters
file?.txt # exactly one character
file[123].txt # one of the listed characters
* से किसी भी Characters को Match करना
Asterisk characters के किसी भी sequence को match करता है, कुछ भी न होने को भी शामिल करते हुए। Bash command चलने से पहले *.txt को current directory में हर matching filename की एक list में expand कर देता है।
उदाहरण: Matching Any Characters with *
#!/bin/bash
touch a.txt b.txt c.log
echo *.txt
rm -f a.txt b.txt c.log
Login to try C/C++/Java/PHP code in the editor
? से एक Single Character को Match करना
Question mark exactly एक arbitrary character match करता है, न ज़्यादा न कम, जो file?.txt जैसे fixed-width patterns के लिए useful है जो file1.txt से match करता है लेकिन file10.txt से नहीं।
उदाहरण: Matching a Single Character with ?
#!/bin/bash
touch file1.txt file2.txt file10.txt
echo file?.txt
rm -f file1.txt file2.txt file10.txt
Login to try C/C++/Java/PHP code in the editor
[...] से Character Classes
Square brackets उनके अंदर listed set (या range) से कोई भी single character match करते हैं, जैसे [abc] या [0-9], * या ? से ज़्यादा precise control देते हुए।
उदाहरण: Character Classes with [...]
#!/bin/bash
touch report1.txt report2.txt reportX.txt
echo report[0-9].txt
rm -f report1.txt report2.txt reportX.txt
Login to try C/C++/Java/PHP code in the editor
No Matches को Safely Handle करना
अगर एक glob pattern कुछ भी match न करे, तो Bash default रूप से pattern text को unexpanded छोड़ देता है, जो scripts को confuse कर सकता है जो एक असली filename की उम्मीद कर रही हों। nullglob enable करने से एक unmatched pattern कुछ नहीं में expand हो जाता है।
shopt -s nullglob set करें जो glob results पर loop करती हैं, ताकि empty matches एक bogus iteration produce न करें।उदाहरण: Handling No Matches Safely
#!/bin/bash
shopt -s nullglob
matches=(*.nonexistent)
echo "Number of matches: ${#matches[@]}"
shopt -u nullglob
Login to try C/C++/Java/PHP code in the editor
- यह मानना कि
*और?regular expressions हैं; वे glob patterns हैं जिनके अलग rules हैं (*किसी भी string को match करता है,.literal है, कोई भी character नहीं)। - यह भूल जाना कि एक unmatched glob pattern default रूप से एक literal string के रूप में छोड़ दिया जाता है, जो script को silently break कर सकता है (
nullglobया explicit checks इसे fix करते हैं)। - Expansion के बाद glob results को आगे pass करते समय quote न करना, जो spaces वाले filenames को गलत तरीके से split कर देता है।
*किसी भी character के zero या ज़्यादा को match करता है;?exactly एक character match करता है;[...]set में से कोई एक character match करता है।- Glob expansion command चलने से पहले ही होता है, पूरी तरह Bash द्वारा खुद किया जाता है।
shopt -s nullglobएक unmatched pattern को literal pattern text के बजाय कुछ नहीं में expand कर देता है।- Glob patterns regular expressions नहीं हैं, भले ही similar दिखें।
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: