# 4.3 awk आणि sed ने text processing

Source: https://ravindrabagale.com/mr/aws/ch04-linux-advanced-commands/4-3-text-processing-awk-and-sed.html
Language: mr (Marathi with English technical terms)

Log मधले columns काढायला awk आणि text बदलायला sed. Mauli Dairy च्या top client IPs किंवा config मधला port शोधण्यासाठी उपयोगी.

awk: columns वर काम

प्रत्येक line चे $1, $2... fields; default whitespace, -F ने separator बदलतो.

awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head
#  ^ top 10 client IPs hitting your web server

awk -F: '{print $1, $7}' /etc/passwd          # user name and shell
awk -F: '$3 >= 1000 {print $1}' /etc/passwd   # normal (non-system) users
df -h | awk 'NR>1 {print $5, $6}'             # usage % and mount point
awk '{sum += $10} END {print sum/1024/1024 " MB"}' /var/log/nginx/access.log  # bytes served

पहिलं उदाहरण access log मधले top client IP counts देते. /etc/passwd मध्ये colon separator; $1 user, $7 shell. UID ≥1000 हा अनेक distros वर सामान्य user चा संकेत आहे, सार्वत्रिक नियम नाही. Access log च्या $10 bytes साठी तुमचा actual log format तपासा.

sed: find-and-replace

sed 's/http/https/' file.txt              # replace first match per line (prints result)
sed 's/http/https/g' file.txt             # replace all matches
sed -i 's/Listen 80/Listen 8080/' /etc/httpd/conf/httpd.conf   # edit file in place
sed -i.bak 's/old/new/g' config.ini       # in place, keep backup config.ini.bak
sed -n '10,20p' file.txt                  # print only lines 10-20
sed '/^#/d' file.txt                      # delete comment lines

साधा s/old/new/ प्रत्येक line चा पहिला match बदलतो; g सर्व matches. -n आणि p ने निवडक lines; /^#/d comments काढतो. -i मूळ file बदलतो, -i.bak backup ठेवतो.

Lab

awk -F: '{print $1, $7}' /etc/passwd run करा. मग cp /etc/hosts ~/hosts.test. आधी sed 's/localhost/mauli-local/g' ~/hosts.test ने preview, मग sed -i.bak 's/localhost/mauli-local/g' ~/hosts.test ने practice copy बदला.

रवींद्र बागले यांची tip

Live config वर sed -i आधी वापरू नका. Preview, backup आणि मग nginx -t किंवा apachectl configtest असा क्रम ठेवा.
