πŸ“€ Basic Output Redirection: >

Syntax:

command > filename
  • Redirects standard output (stdout) to a file.
  • Overwrites the file if it exists.
  • Creates the file if it doesn’t exist.

βœ… Example:

echo "Apple" > fruits.txt

Creates fruits.txt with:

Apple

πŸ“› Warning: > wipes existing contents.


πŸ“€ Appending Output: >>

Syntax:

command >> filename
  • Appends stdout to the end of the file.
  • Keeps existing content.

βœ… Example:

echo "Banana" >> fruits.txt

Now fruits.txt contains:

Apple
Banana

πŸ” Using Redirection with Commands: sort and grep

βœ… sort Example:

sort names.txt > sorted.txt
  • Takes names.txt, sorts the lines, and saves them in sorted.txt.

βœ… grep Example:

grep "John" names.txt > johns.txt
  • Searches for lines containing "John" in names.txt.
  • Saves the matching lines to johns.txt.

βœ… Append grep results:

grep "Doe" names.txt >> johns.txt
  • Adds matches for β€œDoe” to the end of johns.txt.

πŸ“ Create or Empty a File:

You can create or wipe a file with this simple syntax:

> emptyfile.txt
  • Creates emptyfile.txt if it doesn’t exist.
  • Clears the contents if it does exist.