← Back to Bash Course | Chapter 10: Text Processing Tools | Lesson 5 of 12

awk की Basics

awk text की हर line को automatically columns में split करता है और आपको small programs लिखने देता है जो उन columns पर act करें।
Syntax
bash
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

bash
#!/bin/bash
printf "Alice 30 Engineer\nBob 25 Designer\n" | awk '{print $1}'

Custom Field Separator

-F वह character (या pattern) set करता है जो fields split करने के लिए उपयोग होता है, जो CSV जैसे structured data के लिए essential है जहां commas whitespace के बजाय values को separate करते हैं।

उदाहरण: Custom Field Separator

bash
#!/bin/bash
echo "alice,30,engineer" | awk -F, '{print $2}'

NF और NR उपयोग करना

NF current line पर fields की संख्या रखता है, और NR पूरे input के across current line number (record number) रखता है, दोनों rows filter या validate करने के लिए useful हैं।

उदाहरण: Using NF and NR

bash
#!/bin/bash
printf "a b c\nx y\n" | awk '{print "line", NR, "has", NF, "fields"}'

Simple Conditions और Arithmetic

awk programs action block से पहले conditions शामिल कर सकते हैं, इसलिए condition { action } सिर्फ matching lines पर action चलाता है, और awk field values पर directly normal arithmetic support करता है।

उदाहरण: Simple Conditions and Arithmetic

bash
#!/bin/bash
printf "apple 3\nbanana 7\ncherry 1\n" | awk '$2 > 2 { print $1, $2 * 10 }'
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. यह भूल जाना कि $0 पूरी line को refer करता है, जबकि $1, $2, आदि individual fields को refer करते हैं।
  2. यह मान लेना कि fields हमेशा एक single space पर split होते हैं; default field separator whitespace का कोई भी run है, और इसे बदलने के लिए -F चाहिए।
  3. One-liner से ज़्यादा किसी भी चीज़ के लिए -f script.awk उपयोग करने के बजाय command line पर directly complex logic लिखना, quoting को एक nightmare बनाते हुए।
चैप्टर सारांश
  • awk हर input line को fields में split करता है, $1, $2, ... के रूप में accessible, $0 पूरी line मतलब और NF fields की संख्या के साथ।
  • -F field separator set करता है, जैसे comma-separated data के लिए -F,।
  • awk '{print $1}' हर line का सिर्फ पहला field print करता है।
  • NR current line (record) number रखता है, जो position से filter करने के लिए handy है।
🔒

Chapter Quiz — Complete all 12 topics to unlock

0/12 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.