Zsh Shell Tutorial #14: Master File Operations
Video: Zsh Shell Tutorial #14: Master File Operations by Taught by Celeste AI - AI Coding Coach
Watch full page →Zsh Shell Tutorial #14: Master File Operations
Mastering file operations in Zsh is essential for effective shell scripting. This tutorial covers reading files line by line or fully, writing and appending data, testing file properties, and managing directories using commands like mkdir, cp, find, and glob patterns.
Code
# Reading entire file content into a variable
content=$(cat filename.txt)
# Reading file line by line
while IFS= read -r line; do
echo "Line: $line"
done < filename.txt
# Counting lines and words
lines=$(wc -l < filename.txt)
words=$(wc -w < filename.txt)
echo "Lines: $lines, Words: $words"
# Searching for a pattern using grep
grep "pattern" filename.txt
# Writing to a file (overwrite)
echo "New content" > output.txt
# Appending to a file
echo "Additional line" >> output.txt
# Using a here document (heredoc) to write multiple lines
cat << EOF > heredoc.txt
Line 1
Line 2
EOF
# Using tee to write and display output simultaneously
echo "Log entry" | tee -a logfile.txt
# File tests
if [[ -e filename.txt ]]; then echo "File exists"; fi
if [[ -f filename.txt ]]; then echo "Is a regular file"; fi
if [[ -d somedir ]]; then echo "Is a directory"; fi
if [[ -r filename.txt ]]; then echo "Readable"; fi
if [[ -w filename.txt ]]; then echo "Writable"; fi
if [[ -x script.sh ]]; then echo "Executable"; fi
if [[ -s filename.txt ]]; then echo "File is not empty"; fi
# Creating directories recursively
mkdir -p parentdir/childdir
# Copying directories recursively
cp -r sourcedir targetdir
# Finding files recursively by name
find . -name "*.txt"
# Using glob pattern to match files recursively
for file in **/*.txt; do
echo "Found file: $file"
done
Key Points
- Use command substitution and while-read loops to read files fully or line by line in Zsh.
- Redirect output with > to overwrite and >> to append to files, or use heredocs for multiline input.
- Test file existence and permissions with conditional expressions like -e, -f, -d, -r, -w, -x, and -s.
- Create directories with mkdir -p and copy them recursively with cp -r for effective directory management.
- Leverage find and recursive glob patterns (**/*.ext) to locate files efficiently in nested directories.