Working with files is a fundamental aspect of Linux scripting. This tutorial will guide you through the process of reading from and writing to files, exploring various methods and techniques in a Linux environment.
To read the entire content of a file, you can use commands like cat
or echo
along with command substitution:
file_content=$(cat filename.txt)
echo "$file_content"
To read a file line by line, you can use a while
loop with the read
command:
while IFS= read -r line; do
echo "Line: $line"
done < filename.txt
Here, IFS
is set to preserve leading and trailing whitespaces in each line.
Commands like awk
and sed
provide powerful text-processing capabilities. For example, using awk
to print specific columns:
awk '{print $2}' filename.txt
Before reading from a file, it's advisable to check if the file exists:
filename="example.txt"
if [ -e "$filename" ]; then
file_content=$(cat "$filename")
echo "$file_content"
else
echo "File not found: $filename"
fi
To write content to a file, you can use redirection (>
or >>
):
echo "Hello, World!" > output.txt # Overwrites the file
echo "Appended Text" >> output.txt # Appends to the file
The printf
command provides more formatting options:
printf "Name: %s\nAge: %d\n" "John" 25 > profile.txt
To append multiple lines to a file, you can use a here document:
cat <<EOF >> output.txt
Line 1
Line 2
Line 3
EOF
The echo
command is suitable for simple text:
echo "New line" >> output.txt
Reading from and writing to files is a crucial part of Linux scripting. Whether you need to process log files, configure settings, or generate reports, mastering these file manipulation techniques will empower you to create versatile and efficient scripts. Experiment with these methods to handle file operations effectively in your Linux scripts.