Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม Bash

Rename ไฟล์ใน Linux ด้วยคำสั่ง mv - คู่มือทีละขั้นตอน

วิธีใช้คำสั่ง mv ใน Linux

คำสั่ง mv built-in ใช้ rename ไฟล์ได้ Syntax:

mv [options] source_file destination_file

Options ที่มีประโยชน์:

  • -v, --verbose: แสดงรายละเอียดการทำงาน
  • -i, --interactive: prompt ก่อน rename

ตัวอย่าง: rename index.html เป็น web_page.html

mv index.html web_page.html
ls
# web_page.html

Rename ไฟล์จำนวนมาก (Bulk) ด้วย mv

Script rename หลายไฟล์พร้อมกันด้วย loop และ mv

ไฟล์ .js 3 ไฟล์: index.js, config.js, blog.js -> ต้องการเปลี่ยนเป็น .html

for f in *.js; do mv -- "$f" "${f%.js}.html"; done

อธิบาย:

  • for f in *.js: loop ทุกไฟล์ .js ใน directory
  • mv -- "$f" "${f%.js}.html": rename แต่ละไฟล์ ชื่อใหม่ = ชื่อเดิมตัด .js ออก + .html
  • done: จบ loop

ผลลัพธ์: index.html, config.html, blog.html

สรุป

Rename ไฟล์ใน CLI ง่ายและทรงพลังเมื่อนำไปใช้ใน script สำหรับ bulk operations หรือ schedule ได้