Copy (cp) Examples
Example 1: Copy with Backup Preservation
cp --backup=t ~/Documents/report.txt ~/Backups/
Explanation:
- --backup=t ensures that if report.txt already exists in
Backups/, it will be renamed with a timestamp (report.txt.~1~)
instead of being overwritten.
- Useful when you want to keep incremental backups rather than
losing previous versions.
Example 2: Copy Only Newer Files (Update)
cp -u ~/Downloads/*.pdf ~/Documents/Books/
Explanation:
- -u (update) copies only if the source file is newer than the
destination file or if the file doesn’t exist in the destination.
- Prevents unnecessary copying of unchanged files.
Example 3: Copy with Verbose and Interactive Confirmation
cp -iv ~/Pictures/*.jpg ~/Vacation_Photos/
Explanation:
- -i prompts before overwriting any existing files.
- -v (verbose) shows which files are being copied in real-time.
- Useful when you want to avoid accidental overwrites and track
progress.
Renaming (mv) Examples
Example 1: Batch Rename Files with Sequential Numbers
count=1
for file in *.log; do
mv "$file" "log_$(printf "%03d" $count).txt"
((count++))
done
Explanation:
- Renames all .log files to log_001.txt, log_002.txt, etc.
- printf "%03d" ensures 3-digit numbering (e.g., 001 instead of
1).
- Useful for organizing log files systematically.
Example 2: Lowercase All Filenames
for file in *; do
mv "$file" "$(echo $file | tr '[:upper:]' '[:lower:]')"
done
Explanation:
- tr '[:upper:]' '[:lower:]' converts uppercase letters to
lowercase.
- Example: File.TXT → file.txt.
- Helps standardize filenames for scripting.
Example 3: Swap Filenames (Without Temporary File)
mv file1.txt file1.tmp && mv file2.txt file1.txt && mv file1.tmp
file2.txt
Explanation:
- Temporarily renames file1.txt to file1.tmp.
- Moves file2.txt to file1.txt.
- Finally, renames file1.tmp to file2.txt.
- Useful when you need to swap two files quickly.
Example 4: Add Prefix to Filenames
for file in *.csv; do
mv "$file" "data_$file"
done
Explanation:
- Adds data_ prefix to all .csv files (e.g., sales.csv →
data_sales.csv).
- Helps categorize files in a directory.