Length/Substring के लिए Parameter Expansion
In this page:
${#string}
${string:position:length}
${string:position}
${#s} से String Length Pana
${#s} variable s में currently stored characters की संख्या में expand होता है, जो Bash में standard length-checking idiom है। यह characters count करता है, bytes नहीं, ज़्यादातर standard configurations के लिए locale-aware तरीके से।
उदाहरण: Getting String Length with ${#s}
#!/bin/bash
word="Bash"
echo "The word '$word' has ${#word} characters"
Login to try C/C++/Java/PHP code in the editor
${s:pos:len} से एक Substring निकालना
${s:pos:len} s से zero-based index pos से शुरू करके len characters निकालता है। यह एक purely Bash built-in operation है, cut या awk जैसे किसी external tool की ज़रूरत के बिना।
उदाहरण: Extracting a Substring with ${s:pos:len}
#!/bin/bash
sentence="The quick brown fox"
word=${sentence:4:5}
echo "Extracted word: $word"
Login to try C/C++/Java/PHP code in the editor
Length Omit करना
Length argument छोड़ देना, ${s:pos}, index pos से string के end तक सब कुछ निकालता है। यह convenient है जब आपको ठीक से पता नहीं या care नहीं कि बाकी बचा text कितना लंबा है।
उदाहरण: Omitting the Length
#!/bin/bash
path="/usr/local/bin/mytool"
remainder=${path:5}
echo "Everything after index 5: $remainder"
Login to try C/C++/Java/PHP code in the editor
Negative Starting Position
एक negative pos, एक leading space के साथ लिखा हुआ जैसे ${s: -4}, string के beginning से नहीं बल्कि end से backward count करता है। किसी string के last few characters, जैसे एक file extension, पकड़ने का यह एक quick तरीका है।
${filename:-4} (space के बिना) इसके बजाय default-value expansion trigger करेगा, substring extraction नहीं।उदाहरण: Negative Starting Position
#!/bin/bash
filename="report_final.txt"
last_four=${filename: -4}
echo "Last four characters: $last_four"
Login to try C/C++/Java/PHP code in the editor
${#s}(stringsकी length) को${#arr[@]}(एक array की length) से confuse करना;#prefix दोनों cases में 'length of' का मतलब है, लेकिन इसके बाद क्या आता है यह decide करता है कि यह एक string है या array count।- यह मान लेना कि
${s:pos:len}कुछ और tools जैसे one-based indexing उपयोग करता है; Bash string indexing zero-based है, तो${s:0:1}पहला character है। - यह भूल जाना कि एक negative starting position को minus sign से पहले एक space चाहिए (
${s: -3}) ताकि इसे${var:-default}expansion के रूप में parse होने से बचाया जाए substring extraction के बजाय।
${#s}stringsमें characters की संख्या देता है।${s:pos:len}zero-based positionposसे शुरू करकेlencharacters निकालता है।${s:pos}मेंlenomit करनाposसे string के end तक सब कुछ निकालता है।- एक negative
posstring के end से backward count करता है, लेकिन:-के साथ ambiguity से बचने के लिए एक leading space या parentheses चाहिए।
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: