# awk आणि sed ने text processing

Source: https://ravindrabagale.com/mr/cyber/part-02/ch06-linux-advanced-commands/6-3-text-processing-awk-and-sed.html
Language: mr (Marathi with English technical terms)

awk columns/fields process करायला आणि sed text search/replace करायला उपयोगी पडतात. Logs आणि configuration automation मध्ये दोन्ही वारंवार वापरतात.

awk: fields वर काम

प्रत्येक line चे $1, $2 असे fields होतात. Default whitespace separator; -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

पहिली pipeline पहिला field IP आहे असं गृहीत धरून request counts काढते. sort, uniq -c आणि numeric reverse sort ने top IPs दिसतात. /etc/passwd colon-separated असल्याने -F:; पहिला field username आणि सातवा shell. UID ≥1000 हा काही distributions मध्ये सामान्य users साठी उपयोगी heuristic आहे; absolute rule नाही.

NR>1 header वगळतो. शेवटचं bytes-sum example Nginx log format मध्ये bytes दहाव्या field मध्ये आहेत असं गृहीत धरतं. तुमचा format वेगळा असेल किंवा value “-” असेल तर आधी data तपासा.

sed: stream editor

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 '10,20p' ठराविक lines दाखवतो. /^#/d # ने सुरू होणाऱ्या lines output मधून काढतो. -i original file बदलतो; -i.bak backup ठेवण्याचं Linux/GNU sed example आहे.

बदल करण्याआधी output पाहा

पहिल्यांदा -i शिवाय चालवून output inspect करा. Pattern चुकीचा असेल तर original file सुरक्षित राहते. योग्य result आल्यावरच backup सह edit करा आणि service config validate करा.

Security मध्ये उपयोग

Top IP list मध्ये scanning किंवा brute-force source दिसू शकतो, पण जास्त requests म्हणजे attackच असं नाही. Proxy/NAT मागे अनेक users असू शकतात. Request paths, statuses आणि वेळ यांचा context तपासा.

Practice

/etc/passwd मधून shell /bin/bash असलेले usernames print करा. Sed ने config च्या lines 5–10 print करा. मग original ऐवजी copy मधल्या comments काढून पाहा.

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

Live config वर लगेच sed -i चालवू नका. आधी preview, मग -i.bak आणि शेवटी configuration check—अशी सवय ठेवा.
