Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> สมาร์ทโฟน >> Linux

Linux Command Line Magic: Find and Replace ด้วย sed

คู่มือนี้สอนใช้ sed (Stream Editor) Find and Replace ข้อความในไฟล์ ไฟล์หลายไฟล์ และ Directory ทั้งหมด

Syntax พื้นฐาน

sed -i 's/old_text/new_text/g' filename

ตัวอย่าง: เปลี่ยน IP Address ใน Config

# ก่อน
cat database.txt
LOCAL_DATABASE = 192.168.1.16
LOCAL_DIR = /home/calvin/
PROD_DB = 192.168.1.16

# แทนที่ทั้งไฟล์
sed -i 's/192.168.1.16/192.168.1.22/g' database.txt

# หลัง
cat database.txt
LOCAL_DATABASE = 192.168.1.22
LOCAL_DIR = /home/calvin/
PROD_DB = 192.168.1.22

Delimiter ตัวเลือก (เมื่อ Pattern มี /)

# ใช้ | แทน /
sed -i 's|/old/path|/new/path|g' file

# ใช้ # แทน
sed -i 's#https://old.com#https://new.com#g' file

Find and Replace ในหลายไฟล์ (Directory)

# ไฟล์ .txt ใน Current Directory เท่านั้น (ไม่ Recursive)
find . -maxdepth 1 -name "*.txt" -type f -exec sed -i 's/wine/champagne/g' {} \;

# Recursive (ทุกโฟลเดอร์ย่อย)
find . -name "*.txt" -type f -exec sed -i 's/wine/champagne/g' {} \;

# ใช้ xargs (เร็วกว่า -exec)
find . -name "*.txt" -type f -print0 | xargs -0 sed -i 's/wine/champagne/g'

Backup ก่อนแก้ไข (แนะนำ)

# สร้าง backup .bak
sed -i.bak 's/old/new/g' file.txt

# หรือ backup ทั้งโฟลเดอร์ก่อน
cp -r /etc/nginx /etc/nginx.backup.$(date +%F)

Regex Patterns ที่มีประโยชน์

ส่วนคำอธิบาย
-iIn-place (แก้ไขไฟล์ต้นฉบับ)
sSubstitute
/old/new/Pattern และ Replacement (Delimiter = /)
gGlobal (ทุกครั้งในบรรทัด) - ไม่ใส่ = แค่ครั้งแรกต่อบรรทัด

ตัวอย่างขั้นสูง

# Swap 2 คำ: "foo bar" -> "bar foo"
sed -i 's/\(foo\) \(bar\)/\2 \1/g' file

# เพิ่ม Comment (#) หน้าบรรทัดที่มี error
sed -i '/error/s/^/# /' file

# ลบบรรทัดว่าง
sed -i '/^$/d' file

# แทนที่ Newline (ต้องใช้ z option หรือ tr)
sed -z 's/\n/,/g' file

ทางเลือกอื่น

  • perl -pi -e 's/old/new/g' file - Perl regex ทรงพลังกว่า
  • rpl - Tool 专门 for find/replace recursive
  • ripgrep (rg) + sd - Modern, Fast, Rust-based

sed เป็นเครื่องมือคลาสสิกที่ทุก SysAdmin/Dev ต้องรู้ จะช่วยประหยัดเวลามากในการ Refactor Config/Code

Patternความหมาย
^patternต้นบรรทัด
pattern$ท้ายบรรทัด
\bword\bWord boundary (คำเต็ม)
[0-9]\+ตัวเลข 1 หลักขึ้นไป
\(.*\)Capture group (ใช้ \1 ใน replacement)