5 Ways to Empty a File on Linux
Like most operations on any Operating System, there are several ways to do basic file manipulation on Linux. Below are 5 different ways to empty a file.
Simple Redirection
Redirection is usually used to output command results to a file. However, if we redirect “nothing” to a file, we can overwrite it with a blank file. Redirection can be done using a “>” greater-than symbol or a “|” pipe symbol.
# > file.txt or # :> file.txt
REDIRECT THE echo command
Use the echo command to redirect null values to a file.
# echo -n > file.txt
n
do not output the trailing newline.
UsE THE truncate command
Use the truncate command to shrink or expand the size of a file to the size specified by the s
option value. Use zero to make the file empty.
# truncate -s 0 file.txt or # truncate file.txt --size 0
REDIRECT THE /dev/null device
The null device is usually used for disposing of unwanted output streams of a process or as a empty file for input streams or a redirection operation.
# cat /dev/null > file.txt
or
# cp /dev/null file.txt
cp: overwrite 'file.txt'? y
SCRIPT THE Vim Editor
Vim is a text editor built to make creating and changing any kind of text very efficient. It is included as “vi” in most Linux/Unix systems.
# ex -sc ':%d|x' file.txt or # ex -sc ':1,$d|x' file.txt
ex
: Enter into Ex modes
: Silent; do not display promptsc
: Run the given ex command upon startup:
: Invoke an ex command%
: Choose all the linesd
: Delete selected linesx
: save and close2g.txt
: input filename
Average Rating