Pipes से Tools जोड़ना
In this page:
command1 | command2 | command3
grep "pattern" file | cut -d'delimiter' -f field | sort | uniq -c
A Realistic Log Analysis Pipeline
यह pipeline log lines को errors के लिए filter करता है, responsible module का नाम extract करता है, और हर module कितनी बार appear होता है यह count करता है, grep, awk, sort, और uniq -c को combine करके एक useful report में।
उदाहरण: A Realistic Log Analysis Pipeline
#!/bin/bash
cat > app.log <<'EOF'
2024-01-01 INFO auth: login ok
2024-01-01 ERROR db: connection lost
2024-01-01 ERROR auth: bad token
2024-01-01 ERROR db: timeout
2024-01-01 INFO db: reconnected
EOF
grep "ERROR" app.log | awk '{print $3}' | sort | uniq -c | sort -rn
rm -f app.log
Login to try C/C++/Java/PHP code in the editor
Building the Pipeline Incrementally
एक five-stage pipeline को एक ही attempt में लिखने के बजाय, इसे एक समय में एक stage बनाएं और verify करें ताकि हर addition का effect आगे बढ़ने से पहले clear हो।
उदाहरण: Building the Pipeline Incrementally
#!/bin/bash
cat > data.csv <<'EOF'
name,score
alice,88
bob,42
carol,95
dave,60
EOF
echo "stage 1: skip header"
tail -n +2 data.csv
echo "stage 2: extract scores"
tail -n +2 data.csv | cut -d, -f2
echo "stage 3: sort numerically, descending"
tail -n +2 data.csv | cut -d, -f2 | sort -rn
rm -f data.csv
Login to try C/C++/Java/PHP code in the editor
Combining grep, cut, and wc
एक छोटा pipeline एक concrete question सीधे answer कर सकता है, जैसे "कितनी configuration lines एक boolean को true set करती हैं", बिना कोई custom parsing code लिखे।
उदाहरण: Combining grep, cut, and wc
#!/bin/bash
cat > settings.conf <<'EOF'
debug=true
verbose=false
cache=true
retry=true
EOF
count=$(grep "=true" settings.conf | cut -d= -f1 | wc -l)
echo "Number of enabled settings: $count"
rm -f settings.conf
Login to try C/C++/Java/PHP code in the editor
- सब कुछ एक enormous awk या sed command में करने की कोशिश करना बजाय कई simpler tools compose करने के, pipeline को पढ़ना और debug करना मुश्किल बनाते हुए।
- Pipeline के हर stage को independently test न करना उन्हें chain करने से पहले, जिससे यह बताना मुश्किल हो जाता है कि किस stage ने bug introduce किया।
- यह भूल जाना कि pipeline के बाद वाले stages सिर्फ वह देखते हैं जो पहले वाले stages ने already transform किया है, original raw input नहीं।
- एक pipeline को incrementally बनाना, हर added stage के बाद output check करते हुए, इसे एक साथ लिखने से debugging कहीं आसान बनाता है।
- grep, sed, awk, cut, sort, uniq, और wc naturally combine होते हैं क्योंकि वे सभी default रूप से stdin पढ़ते और stdout लिखते हैं।
- एक realistic pipeline अक्सर ऐसा दिखता है: filter (grep) -> reshape (awk/cut) -> order (sort) -> summarize (uniq -c/wc)।
- दो या तीन stages से ज़्यादा किसी भी चीज़ के लिए trailing
|के साथ एक pipeline को multiple lines में format करना readability सुधारता है।
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: