Community Tutorials Linux Basics كيفية البحث والاستبدال في النصوص باستخدام sed و awk
كيفية البحث والاستبدال في النصوص باستخدام sed و awk
LINUX BASICS

كيفية البحث والاستبدال في النصوص باستخدام sed و awk

SKYLINE Knowledge Base
Photo by Sigmund on Unsplash

دليل عملي خطوة بخطوة لـ كيفية البحث والاستبدال في النصوص باستخدام sed و awk. أوامر مختبرة في الإنتاج، متطلبات مسبقة، تحقق نهائي وروابط لمواضيع ذات صلة.

sed و awk على كل نظام Unix منذ الـ70s. أبطأ من Python للكتابة، لكن لاستبدال نص لمرة واحدة، تصل لـ sed؛ لمتوسط عمود، تصل لـ awk.

المتطلبات المسبقة

  • shell على Linux/macOS.

الخطوة 1: sed — استبدال بسيط

sed 's/old/new/' file.txt
sed 's/old/new/g' file.txt
sed -i.bak 's/old/new/g' file.txt

على macOS:

sed -i '' 's/old/new/g' file.txt

الخطوة 2: نطاقات

sed -n '5,10p' file.txt
sed '5,10d' file.txt
sed '/^#/d' file.txt
sed '/^$/d' file.txt
sed '/START/,/END/d' file.txt

الخطوة 3: مجموعات الالتقاط

sed -E 's/^([^:]+): (.+)$/\2: \1/' file.txt
sed -E 's/version = ([0-9.]+)/version = "\1"/' config.toml

الخطوة 4: awk

awk '{ print $1 }' file.txt
awk '$1 == "ERROR" { print $3 }' app.log
awk '{ sum += $2 } END { print sum }' nums.txt
awk '{ sum += $2; n++ } END { printf "%.2f\n", sum/n }' nums.txt

الخطوة 5: محددات مخصصة

awk -F, '{ print $2 }' data.csv
awk -F: '{ print $1 }' /etc/passwd

الخطوة 6: التجميع والعد

awk '{ count[$9]++ } END { for (s in count) print s, count[s] }' access.log
awk '{ ip[$1]++ } END { for (i in ip) print ip[i], i }' access.log | sort -nr | head -10

الخطوة 7: pipelines

awk '$9 ~ /^5/ { print $7 }' access.log \
  | sort | uniq -c | sort -nr | head -20

الخطوة 8: متى تذهب إلى Python

أكثر من 3 pipes أو أي حالة عبر أكثر من حقل — انتقل إلى Python.

التحقق

sed --version | head -1
awk --version 2>&1 | head -1

الخاتمة

ثلاثة أنماط للتذكر: sed 's/old/new/g'، awk -F, '{print $2}'، و awk '{count[$1]++}END{...}'.

الخطوات التالية

SKYLINE Engineering

@skyline

The engineering team at SKYLINE Industrial Solutions. We publish field-tested guides drawn from real KSA and GCC deployments.

See author profile
SKYLINE engineering services

Need this implemented for you?

Reading is free — building it right takes a team. SKYLINE engineers ship Linux Basics for Aramco vendors, banks, hospitals and government agencies across Saudi Arabia. Talk to us before you start.

Aramco Approved Contractor ISO 9001 · ISO 27001 SAMA CSF aligned NCA ECC ready 247+ KSA clients

Comments

0 total · 0 threads
Be the first to leave a comment.