ITclub

العودة إلى Linux
محاضرة 4

CLI: Text File Manipulation and Advanced Commands

التعامل مع الملفات النصية (`touch`, `cat`, `echo`, `nano`) وأوامر متقدمة (`find`, `grep`, `sort`).

ملخص المحاضرة

🐧 Lecture 4: CLI Text File Manipulation and Advanced Commands

This lecture expands on CLI skills, focusing on creating, reading, and editing text files, as well as introducing more powerful commands for searching, viewing, and sorting data.

Basic File Creation and Editing

  • touch: Creates a new, empty file. You can create multiple files at once (e.g., touch main.js script.js sum.py).
  • cat: (Concatenate) Shows the entire content of a file on the terminal. If the file is empty, it shows nothing.
  • echo: Used to write text.
    • echo "Text" > file.txt: (Overwrite) Puts the text "Text" into file.txt. If the file already has content, it will be deleted and replaced.
    • echo "Text" >> file.txt: (Append) Adds the text "Text" to the end of file.txt without deleting existing content.
  • mv: (Move) This command has two functions:
    1. Move: mv file.txt /path/to/dir moves the file to a new directory.
    2. Rename: mv old-name.txt new-name.txt renames the file.
  • nano: A terminal-based text editor.
    • nano names.txt: Opens the file for editing.
    • Ctrl + O: Saves the changes (Write Out).
    • Ctrl + X: Exits the editor.

Advanced File Interaction

  • find: Searches for files or directories.
    • find . -name "*.js": Finds all files in the current directory (.) whose names end in .js.
    • find . -name "*.js" -delete: Finds all files ending in .js and deletes them.
  • less: An interactive file viewer for large files. It allows you to:
    • Scroll down (Space) and up (b).
    • Go to the end (G) or start (g).
    • Search (/word).
    • Quit (q).
  • more: An older, simpler viewer. It does not allow scrolling backward and exits automatically at the end of the file.
  • head: Shows the first 10 lines of a file by default.
    • head -n 5 file.txt: Shows only the first 5 lines.
  • tail: Shows the last 10 lines of a file.
    • tail -f file.txt: (Follow) Monitors the file in real-time and shows any new lines as they are added.
  • grep: Searches for specific text inside files.
    • grep "Nolan" file.txt: Finds lines containing "Nolan".
    • grep -i "nolan" file.txt: Case-insensitive search.
    • grep -n "Nolan" file.txt: Shows the line numbers of matches.
    • grep -c "Nolan" file.txt: Counts how many lines match.
  • sort: Sorts the lines of a file alphabetically.
    • sort -r file.txt: Sorts in reverse (descending) order.
    • sort -u file.txt: (Unique) Sorts and removes duplicate lines.