Skip to content

Latest commit

 

History

History
98 lines (63 loc) · 2.42 KB

01.Reading_from_and_writing_to_files.md

File metadata and controls

98 lines (63 loc) · 2.42 KB

Reading from and Writing to Files in Linux Scripting

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.

Reading from Files

Reading Entire File Content

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"

Reading Line by Line

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.

Using awk and sed

Commands like awk and sed provide powerful text-processing capabilities. For example, using awk to print specific columns:

awk '{print $2}' filename.txt

Checking File Existence

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

Writing to Files

Writing Entire Content

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

Writing with printf

The printf command provides more formatting options:

printf "Name: %s\nAge: %d\n" "John" 25 > profile.txt

Appending Multiple Lines

To append multiple lines to a file, you can use a here document:

cat <<EOF >> output.txt
Line 1
Line 2
Line 3
EOF

Using echo

The echo command is suitable for simple text:

echo "New line" >> output.txt

Conclusion

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.