Text Editors (vim, nano, emacs basics)
Category: Intermediate Linux Commands
Type: Linux Commands
Generated on: 2025-07-10 03:12:17
For: System Administration, Development & Technical Interviews
Okay, here is a comprehensive cheatsheet for text editors (vim, nano, emacs) and intermediate Linux commands, tailored for sysadmins and developers, with the requested structure, style guidelines, and focus on practical, real-world scenarios.
Text Editors & Intermediate Linux Commands Cheatsheet (Sysadmin/Developer Focused)
Section titled “Text Editors & Intermediate Linux Commands Cheatsheet (Sysadmin/Developer Focused)”I. Text Editors (vim, nano, emacs)
Section titled “I. Text Editors (vim, nano, emacs)”A. vim (Vi Improved)
Section titled “A. vim (Vi Improved)”1. Command Overview
Section titled “1. Command Overview”- What: A powerful, highly configurable text editor. Modal editing (command mode, insert mode) allows for efficient text manipulation.
- When: Everyday text editing, configuration file editing, software development, scripting. Essential for remote server work where GUI editors are unavailable.
2. Basic Syntax
Section titled “2. Basic Syntax”vim [options] [file...]3. Practical Examples
Section titled “3. Practical Examples”- Open a file:
Terminal window vim my_file.txt - Create a new file:
Terminal window vim new_file.txt - Open multiple files:
Terminal window vim file1.txt file2.txt file3.txt - Open a file at a specific line number:
Terminal window vim +10 my_file.txt # Opens my_file.txt at line 10
4. Common Options
Section titled “4. Common Options”-R: Read-only mode.+: Start editing at the last line.+[num]: Start editing at linenum.-o: Open files in vertical splits.-O: Open files in horizontal splits.-d: Diff mode (compare two files).
5. Advanced Usage
Section titled “5. Advanced Usage”- Using .vimrc: Customize vim’s behavior by editing
~/.vimrc. Example:" Enable syntax highlightingsyntax on" Set tab width to 4 spacesset tabstop=4set shiftwidth=4set expandtab" Show line numbersset number - Macros: Record and replay a sequence of commands.
q[char]: Start recording macro to register[char](e.g.,qa).q: Stop recording.@[char]: Execute the macro in register[char].@@: Execute the last executed macro.
- Search and Replace with Regular Expressions:
:%s/old_text/new_text/g # Replace all occurrences of "old_text" with "new_text" in the entire file.:%s/^\s*//g # Remove leading whitespace from all lines.:%s/\s+$//g # Remove trailing whitespace from all lines.
- Splits and Tabs:
:sp: Split the window horizontally.:vsp: Split the window vertically.:tabnew: Open a new tab.:tabn: Go to the next tab.:tabp: Go to the previous tab.Ctrl-w w: Switch between windows.
6. Tips & Tricks
Section titled “6. Tips & Tricks”- Essential Commands (Normal Mode):
i: Insert mode (before the cursor).a: Append mode (after the cursor).o: Open a new line below the current line.O: Open a new line above the current line.dd: Delete the current line.yy: Yank (copy) the current line.p: Paste after the cursor.P: Paste before the cursor.u: Undo.Ctrl-r: Redo.:w: Save the file.:q: Quit vim.:wq: Save and quit.:q!: Quit without saving (discard changes).G: Go to the end of the file.gg: Go to the beginning of the file.:[line_number]: Go to a specific line number./pattern: Search forpatternforward.?pattern: Search forpatternbackward.n: Find the next occurrence of the search pattern.N: Find the previous occurrence of the search pattern.:%s/old/new/g: Replace all occurrences ofoldwithnew..: Repeat the last command.
- Visual Mode:
v: Character-wise visual selection.V: Line-wise visual selection.Ctrl-v: Block-wise visual selection.
7. Troubleshooting
Section titled “7. Troubleshooting”- “E325: ATTENTION”: Swap file exists. Usually means vim crashed or was improperly closed. Options:
(O)pen Read-Only: View the file without making changes.(E)dit anyway: Edit the file anyway (may cause data loss if another instance is editing).(R)ecover: Attempt to recover the file from the swap file.(D)elete it: Delete the swap file.(Q)uit: Quit.(A)bort: Abort.
- Escaping Insert Mode: Press
Escto return to Normal mode.
8. Related Commands
Section titled “8. Related Commands”vi: The original Vi editor (often a symlink to vim).gvim: GUI version of vim.diff: Compare files.
B. nano
Section titled “B. nano”1. Command Overview
Section titled “1. Command Overview”- What: A simple, easy-to-use text editor, especially suitable for beginners.
- When: Quickly editing configuration files, writing short scripts, basic text editing tasks.
2. Basic Syntax
Section titled “2. Basic Syntax”nano [options] [file...]3. Practical Examples
Section titled “3. Practical Examples”- Open a file:
Terminal window nano my_file.txt - Create a new file:
Terminal window nano new_file.txt
4. Common Options
Section titled “4. Common Options”-w: Disable word wrap.-m: Enable mouse support.-R: Read-only mode.-l: Display line numbers.-t num: Set tab size tonumcolumns.-B: Enable taking backups of files.
5. Advanced Usage
Section titled “5. Advanced Usage”- Using .nanorc: Customize nano’s behavior by editing
~/.nanorc. Example:set tabsize 4set tabstospacesset linenumbersset backup - Search and Replace:
Ctrl+\to initiate the replace operation. - Cut and Paste:
Ctrl+Kto cut a line,Ctrl+Uto paste.
6. Tips & Tricks
Section titled “6. Tips & Tricks”- Keybindings: Displayed at the bottom of the screen.
^representsCtrl.Ctrl+G: Get Help.Ctrl+O: Write Out (save).Ctrl+X: Exit.Ctrl+R: Read File (insert file content).Ctrl+W: Where Is (search).Ctrl+\: Replace.Ctrl+K: Cut Text.Ctrl+U: Uncut Text (paste).Ctrl+J: Justify (format paragraph).Ctrl+T: To Spell (spell check).Ctrl+C: Show cursor position.
7. Troubleshooting
Section titled “7. Troubleshooting”- Permissions Issues: Make sure you have write permissions to the file.
- Terminal Size: Nano works best in a terminal with sufficient width and height.
8. Related Commands
Section titled “8. Related Commands”pico: Older, similar editor. Often a symlink to nano.
C. emacs
Section titled “C. emacs”1. Command Overview
Section titled “1. Command Overview”- What: A highly extensible, customizable text editor with a vast ecosystem of extensions and features. More than just a text editor; it’s a complete environment.
- When: Software development, writing documents, managing projects, email, and much more. Requires more initial learning but can be extremely powerful.
2. Basic Syntax
Section titled “2. Basic Syntax”emacs [options] [file...]3. Practical Examples
Section titled “3. Practical Examples”- Open a file:
Terminal window emacs my_file.txt - Create a new file:
Terminal window emacs new_file.txt - Open multiple files:
Terminal window emacs file1.txt file2.txt
4. Common Options
Section titled “4. Common Options”-nw: Run in terminal mode (no GUI).-q: Start Emacs without loading the init file (~/.emacsor~/.emacs.d/init.el).-u user: Load the init file foruser.--daemon: Start Emacs as a daemon process in the background.--eval expr: Evaluate a Lisp expression.
5. Advanced Usage
Section titled “5. Advanced Usage”- Using .emacs.d/init.el: Customize Emacs using Emacs Lisp. Example:
(setq inhibit-startup-message t) ; Disable startup message(global-linum-mode 1) ; Enable line numbers globally(setq tab-width 4) ; Set tab width(setq indent-tabs-mode nil) ; Use spaces instead of tabs(global-auto-revert-mode 1) ; Automatically refresh buffers when files change
- Packages: Extend Emacs with packages from repositories like MELPA. Use
M-x package-install(whereM-xmeansAlt+xon most systems) to install packages. Example:M-x package-install solarized-theme. - Buffers and Windows:
C-x C-f: Find file (open a file in a buffer).C-x C-s: Save buffer.C-x C-b: List buffers.C-x k: Kill buffer.C-x 2: Split window horizontally.C-x 3: Split window vertically.C-x o: Switch to another window.C-x 0: Close current window.C-x 1: Close all other windows.
6. Tips & Tricks
Section titled “6. Tips & Tricks”- Keybindings: Emacs uses
Ctrl(C) andAlt(M) as modifier keys.C-g: Cancel current command.C-h: Help.C-x C-c: Quit Emacs.C-x C-f: Find File (open).C-x C-s: Save File.C-x s: Save all buffers.C-s: Search forward.C-r: Search backward.M-%: Query Replace.C-k: Kill (cut) to end of line.C-y: Yank (paste).M-w: Copy.C-w: Cut.C-a: Go to beginning of line.C-e: Go to end of line.M-<: Go to beginning of file.M->: Go to end of file.C-v: Scroll forward.M-v: Scroll backward.
- Customization: Learn Emacs Lisp to deeply customize the editor.
7. Troubleshooting
Section titled “7. Troubleshooting”- Keybinding Conflicts: Many keybindings are already defined. Use
C-h kfollowed by the key combination to find out what it does. - Init File Errors: Errors in
~/.emacs.d/init.elcan prevent Emacs from starting. Start withemacs -qto bypass the init file and diagnose the problem. - Learning Curve: Emacs has a steep learning curve. Start with the Emacs tutorial (
C-h t).
8. Related Commands
Section titled “8. Related Commands”xemacs: A variant of Emacs with some different features.
II. Intermediate Linux Commands
Section titled “II. Intermediate Linux Commands”A. Process Management
Section titled “A. Process Management”1. Command Overview
Section titled “1. Command Overview”- What: Commands for monitoring, controlling, and managing processes running on the system.
- When: Troubleshooting performance issues, killing runaway processes, managing background tasks.
2. Basic Syntax
Section titled “2. Basic Syntax”ps [options]top [options]kill [options] PIDkillall [options] process_namebg [job_id]fg [job_id]jobs [options]nohup command [arguments] &systemctl [options] command service_name
3. Practical Examples
Section titled “3. Practical Examples”- List all running processes:
Terminal window ps auxUSER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMANDroot 1 0.0 0.0 168304 4944 ? Ss May01 0:05 /sbin/initroot 2 0.0 0.0 0 0 ? S May01 0:00 [kthreadd]... - Find the process ID (PID) of a specific process:
Terminal window ps aux | grep my_process - Kill a process by PID:
Terminal window kill 1234 # Sends SIGTERM (termination signal) - Forcefully kill a process by PID:
Terminal window kill -9 1234 # Sends SIGKILL (immediate termination) - use with caution! - Kill all processes with a specific name:
Terminal window killall my_process - Start a process in the background:
Terminal window long_running_command & - Bring a background process to the foreground:
Terminal window fg %1 # Bring job 1 to the foreground - List all background jobs:
Terminal window jobs[1]+ Running long_running_command & - Run a command that persists even after you close the terminal:
Terminal window nohup long_running_command > output.log 2>&1 & - Start, stop, and restart services using systemctl (systemd):
Terminal window sudo systemctl start nginxsudo systemctl stop nginxsudo systemctl restart nginxsudo systemctl status nginxsudo systemctl enable nginx # Start on bootsudo systemctl disable nginx # Disable on boot
4. Common Options
Section titled “4. Common Options”- ps:
aux: List all processes with detailed information (user, PID, CPU usage, memory usage, etc.).ef: Similar toaux, but with a different format.-u user: List processes owned byuser.
- top:
-u user: Show processes owned byuser.-p PID: Monitor a specific process by PID.q: Quit top.h: Show help.
- kill:
-signal_number: Send a specific signal (e.g.,-9for SIGKILL,-15for SIGTERM).kill -llists signal names and numbers.
- killall:
-u user: Kill processes owned byuser.-e: Exact match for process name.
- jobs:
-l: List process IDs in addition to job information.
- nohup:
>: Redirect standard output.2>&1: Redirect standard error to standard output.
- systemctl:
status: Check the status of a service.start: Start a service.stop: Stop a service.restart: Restart a service.reload: Reload the configuration of a service without restarting.enable: Enable a service to start on boot.disable: Disable a service from starting on boot.is-enabled: Check if a service is enabled to start on boot.list-units: List all systemd units.
5. Advanced Usage
Section titled “5. Advanced Usage”- Monitoring a process and restarting it if it crashes (using
whileloop):Terminal window while true; do./my_processecho "Process crashed, restarting..."sleep 5done - Finding the process consuming the most CPU:
Terminal window ps aux --sort=-%cpu | head -n 10 - Finding the process consuming the most memory:
Terminal window ps aux --sort=-%mem | head -n 10 - Using
reniceto change the priority of a running process:Note: Requires root privileges to decrease the nice value (increase priority).Terminal window renice -n 10 -p 1234 # Increase the priority (lower nice value) of process 1234renice -n 19 -p 1234 # Decrease the priority (higher nice value) of process 1234 - Creating custom systemd service files: Place service files in
/etc/systemd/system/. Example:Then, run[Unit]Description=My Custom ServiceAfter=network.target[Service]User=myuserWorkingDirectory=/home/myuser/my_appExecStart=/home/myuser/my_app/start.shRestart=on-failure[Install]WantedBy=multi-user.targetsudo systemctl daemon-reloadto load the new service file.
6. Tips & Tricks
Section titled “6. Tips & Tricks”- Use
pgrepto find PIDs by name:pgrep my_process - Combine
pgrepandkill:kill $(pgrep my_process) - Use
htopfor an interactive process viewer (requires installation):sudo apt install htop(Debian/Ubuntu) orsudo yum install htop(CentOS/RHEL). - Be careful when using
kill -9. It doesn’t allow the process to clean up or save state, which can lead to data corruption. Trykill(SIGTERM) first. - Use
screenortmuxfor persistent terminal sessions. These allow you to detach and reattach to a terminal session, so your processes continue running even if you close your terminal.
7. Troubleshooting
Section titled “7. Troubleshooting”- “Operation not permitted”: You don’t have sufficient privileges to kill a process. Use
sudo. - Process doesn’t die after
kill: The process might be ignoring the signal. Trykill -9as a last resort. - Service fails to start: Check the systemd journal for errors:
sudo journalctl -u my_service.service
8. Related Commands
Section titled “8. Related Commands”nice: Run a command with a specified priority.renice: Change the priority of a running process.screen,tmux: Terminal multiplexers.systemd-analyze: Analyze systemd boot performance.journalctl: View systemd logs.
B. File System Management
Section titled “B. File System Management”1. Command Overview
Section titled “1. Command Overview”- What: Commands for navigating, creating, modifying, and managing files and directories.
- When: Organizing files, managing storage space, setting permissions, automating file operations.
2. Basic Syntax
Section titled “2. Basic Syntax”cd [directory]pwdls [options] [file...]mkdir [options] directory...rm [options] file...rmdir [options] directory...cp [options] source destinationmv [options] source destinationtouch [options] file...chmod [options] file...chown [options] user:group file...df [options]du [options] [file...]find [path] [expression]tar [options] [file...]
3. Practical Examples
Section titled “3. Practical Examples”- Change directory:
Terminal window cd /var/logcd .. # Go up one levelcd ~ # Go to home directorycd - # Go to the previous directory - Print working directory:
Terminal window pwd - List files and directories:
Terminal window ls -l # Long listing formatls -a # Show hidden filesls -t # Sort by modification timels -lh # Human readable file sizes - Create a directory:
Terminal window mkdir my_directorymkdir -p /path/to/nested/directory # Create parent directories if they don't exist - Remove a file:
Terminal window rm my_file.txt - Remove a directory (must be empty):
Terminal window rmdir my_directory - Remove a directory and its contents (use with extreme caution!):
Terminal window rm -rf my_directory # -r: recursive, -f: force (no prompts) - Copy a file:
Terminal window cp file1.txt file2.txt # Copy file1.txt to file2.txtcp -r directory1 directory2 # Copy directory1 to directory2 recursively - Move/rename a file or directory:
Terminal window mv file1.txt file2.txt # Rename file1.txt to file2.txtmv file1.txt /path/to/destination/ # Move file1.txt to the destination directory - Create an empty file or update the timestamp of an existing file:
Terminal window touch my_file.txt - Change file permissions:
Terminal window chmod 755 my_script.sh # Set permissions to rwxr-xr-xchmod +x my_script.sh # Make the script executablechmod -R 777 /path/to/directory # recursively apply permissions (use with caution) - Change file ownership:
Terminal window sudo chown user:group my_file.txtsudo chown -R user:group /path/to/directory # Recursively change ownership - Check disk space usage:
Terminal window df -h # Human-readable outputdf -i # Show inode usage - Check directory size:
Terminal window du -sh my_directory # Human-readable summarydu -h --max-depth=1 my_directory # Show sizes of subdirectories in my_directory - Find files:
Terminal window find . -name "*.txt" # Find all .txt files in the current directory and its subdirectoriesfind /var/log -type f -mtime -7 # Find files in /var/log modified in the last 7 daysfind . -size +10M # Find files larger than 10MBfind . -user myuser # Find files owned by myuserfind . -perm 755 # Find files with permission 755 - Create a tar archive:
Terminal window tar -cvf archive.tar file1.txt file2.txt directory1 # Create a tar archivetar -czvf archive.tar.gz file1.txt file2.txt directory1 # Create a gzipped tar archivetar -xvf archive.tar # Extract a tar archivetar -xzvf archive.tar.gz # Extract a gzipped tar archivetar -tvf archive.tar # List the contents of a tar archive
4. Common Options
Section titled “4. Common Options”- ls:
-l: Long listing format.-a: Show all files, including hidden files (starting with.).-t: Sort by modification time (newest first).-r: Reverse the order of sorting.-h: Human-readable file sizes (e.g., 1K, 234M, 2G).-S: Sort by file size.
- mkdir:
-p: Create parent directories as needed.
- rm:
-r: Recursive (remove directories and their contents).-f: Force (remove without prompting).-i: Interactive (prompt before each deletion).
- cp:
-r: Recursive (copy directories and their contents).-i: Interactive (prompt before overwriting).-a: Archive (preserve permissions, ownership, and timestamps).
- mv:
-i: Interactive (prompt before overwriting).
- chmod:
[ugo][+-=][rwx](e.g.,chmod u+x file.txt- add execute permission for the owner).u(user),g(group),o(others),a(all).[0-7][0-7][0-7](e.g.,chmod 755 file.txt). Octal representation of permissions.-R: Recursive.
- chown:
-R: Recursive.
- df:
-h: Human-readable output.-i: Show inode usage.
- du:
-s: Summary (show only the total size).-h: Human-readable output.--max-depth=n: Limit the depth of recursion.
- find:
-name pattern: Find files with a specific name pattern.-type f: Find files.-type d: Find directories.-size [+-]size: Find files of a specific size.+for greater than,-for less than.-mtime [+-]days: Find files modified within a certain number of days.-user user: Find files owned by a specific user.-exec command {} \;: Execute a command on each found file.{}is replaced with the filename.\;terminates the command.-ok command {} \;: Like-exec, but prompts for confirmation before executing the command.
- tar:
-c: Create an archive.-x: Extract an archive.-v: Verbose (list files being processed).-f file: Specify the archive filename.-z: Compress with gzip.-j: Compress with bzip2.-t: List the contents of an archive.-C directory: Change todirectorybefore extracting.
5. Advanced Usage
Section titled “5. Advanced Usage”- Finding and deleting files older than 30 days:
Important: Test this with
Terminal window find /path/to/directory -type f -mtime +30 -delete-lsbefore using-deleteto ensure you’re deleting the correct files.Terminal window find /path/to/directory -type f -mtime +30 -ls - Finding files and changing their permissions:
Terminal window find /path/to/directory -type f -name "*.txt" -exec chmod 644 {} \; - Creating a tar archive excluding certain files or directories:
Terminal window tar -czvf archive.tar.gz --exclude='./exclude_directory' --exclude='*.log' ./my_directory - Using
rsyncfor efficient file synchronization (more advanced, but very useful):Terminal window rsync -avz /source/directory/ /destination/directory/rsync -avz user@remote_host:/source/directory/ /destination/directory/ - Creating a hard link and a symbolic link:
Terminal window ln file1.txt hardlink.txt # Create a hard linkln -s file1.txt symlink.txt # Create a symbolic link
6. Tips & Tricks
Section titled “6. Tips & Tricks”- Use tab completion to speed up typing file and directory names.
- Use
!!to repeat the last command. - Use
sudo !!to run the last command with root privileges. - Use wildcards (
*,?,[]) to select multiple files.*.txt: All files ending in.txt.file?.txt: Files likefile1.txt,file2.txt, etc.file[1-5].txt: Files likefile1.txt,file2.txt, …,file5.txt.
- Use
xargsto pass a large number of filenames to a command:Terminal window find . -name "*.txt" | xargs rm # Remove all .txt files - Be extremely careful when using
rm -rf. Double-check the path before running it.
7. Troubleshooting
Section titled “7. Troubleshooting”- “Permission denied”: You don’t have the necessary permissions to access or modify the file or directory. Use
sudoor change the permissions withchmod. - “No such file or directory”: The file or directory you’re trying to access doesn’t exist. Double-check the path.
- “Disk quota exceeded”: You’ve exceeded your disk quota. Delete unnecessary files or request a quota increase.
- “File exists”: The file you’re trying to copy or move already exists. Use the
-ioption to prompt before overwriting.
8. Related Commands
Section titled “8. Related Commands”ln: Create hard links and symbolic links.rsync: Synchronize files and directories.mount,umount: Mount and unmount file systems.fdisk,parted: Partition management tools (use with extreme caution!).mkfs: Create a file system.
C. Networking
Section titled “C. Networking”1. Command Overview
Section titled “1. Command Overview”- What: Commands for configuring, troubleshooting, and monitoring network connections.
- When: Diagnosing network issues, configuring network interfaces, testing connectivity, monitoring network traffic.
2. Basic Syntax
Section titled “2. Basic Syntax”ip [options] addressifconfig [interface] [options](Deprecated, but still commonly used)ping [options] destinationtraceroute [options] destinationnetstat [options](Deprecated, replaced byss)ss [options]nslookup [domain]dig [options] domaincurl [options] URLwget [options] URLssh [options] user@hostscp [options] user@host:file local_filetcpdump [options] [expression]
3. Practical Examples
Section titled “3. Practical Examples”- Show network interface configuration (using
ip):Terminal window ip addr show - Show network interface configuration (using
ifconfig- deprecated):Terminal window ifconfig eth0 - Ping a host:
Terminal window ping google.com - Trace the route to a host:
Terminal window traceroute google.com - List listening ports (using
ss):Terminal window ss -tulnp - List listening ports (using
netstat- deprecated):Terminal window netstat -tulnp - Look up the IP address of a domain (using
nslookup):Terminal window nslookup google.com - Look up DNS records (using
dig):Terminal window dig google.comdig MX google.com # Check mail exchange records - Download a file using
curl:Terminal window curl -O https://example.com/file.txt # Save file to current directorycurl -o my_file.txt https://example.com/file.txt # Save file to my_file.txt - Download a file using
wget:Terminal window wget https://example.com/file.txt - Connect to a remote host using SSH:
Terminal window ssh user@remote_hostssh -p 2222 user@remote_host # Connect to port 2222ssh -i ~/.ssh/my_private_key user@remote_host # Use a specific private key - Copy a file to a remote host using SCP:
Terminal window scp my_file.txt user@remote_host:/path/to/destination/ - Capture network traffic (using
tcpdump- requires root):Terminal window sudo tcpdump -i eth0 -n -vv port 80 # Capture HTTP traffic on eth0sudo tcpdump -i any -n -vv icmp # Capture ICMP traffic on all interfaces
4. Common Options
Section titled “4. Common Options”- ip:
addr show: Show network interface addresses.- `