awk की Basics
In this page:
awk '{print $1}' file_name
awk -F'delimiter' '{print $2}' file_name
awk '{print NR, NF}' file_name
एक Field Print करना
awk text की हर line को automatically whitespace पर fields में split करता है जो $1, $2, और इसी तरह number होते हैं, $0 पूरी line को refer करता है। एक simple {print $1} program हर input line का सिर्फ पहला field print करता है।
उदाहरण: Printing a Field
#!/bin/bash
printf "Alice 30 Engineer\nBob 25 Designer\n" | awk '{print $1}'
Login to try C/C++/Java/PHP code in the editor
Custom Field Separator
-F वह character (या pattern) set करता है जो fields split करने के लिए उपयोग होता है, जो CSV जैसे structured data के लिए essential है जहां commas whitespace के बजाय values को separate करते हैं।
उदाहरण: Custom Field Separator
#!/bin/bash
echo "alice,30,engineer" | awk -F, '{print $2}'
Login to try C/C++/Java/PHP code in the editor
NF और NR उपयोग करना
NF current line पर fields की संख्या रखता है, और NR पूरे input के across current line number (record number) रखता है, दोनों rows filter या validate करने के लिए useful हैं।
उदाहरण: Using NF and NR
#!/bin/bash
printf "a b c\nx y\n" | awk '{print "line", NR, "has", NF, "fields"}'
Login to try C/C++/Java/PHP code in the editor
Simple Conditions और Arithmetic
awk programs action block से पहले conditions शामिल कर सकते हैं, इसलिए condition { action } सिर्फ matching lines पर action चलाता है, और awk field values पर directly normal arithmetic support करता है।
उदाहरण: Simple Conditions and Arithmetic
#!/bin/bash
printf "apple 3\nbanana 7\ncherry 1\n" | awk '$2 > 2 { print $1, $2 * 10 }'
Login to try C/C++/Java/PHP code in the editor
- यह भूल जाना कि
$0पूरी line को refer करता है, जबकि$1,$2, आदि individual fields को refer करते हैं। - यह मान लेना कि fields हमेशा एक single space पर split होते हैं; default field separator whitespace का कोई भी run है, और इसे बदलने के लिए
-Fचाहिए। - One-liner से ज़्यादा किसी भी चीज़ के लिए
-f script.awkउपयोग करने के बजाय command line पर directly complex logic लिखना, quoting को एक nightmare बनाते हुए।
- awk हर input line को fields में split करता है,
$1,$2, ... के रूप में accessible,$0पूरी line मतलब औरNFfields की संख्या के साथ। -Ffield separator set करता है, जैसे comma-separated data के लिए-F,।awk '{print $1}'हर line का सिर्फ पहला field print करता है।NRcurrent line (record) number रखता है, जो position से filter करने के लिए handy है।
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: