π€ 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.txtCreates 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.txtNow 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 insorted.txt.
β
grep Example:
grep "John" names.txt > johns.txt- Searches for lines containing
"John"innames.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.txtif it doesnβt exist. - Clears the contents if it does exist.