5 Ways to Empty a File on Linux

Read Time:1 Min, 25 Sec

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 mode
  • s : Silent; do not display prompts
  • c : Run the given ex command upon startup
  • : : Invoke an ex command
  • % : Choose all the lines
  • d : Delete selected lines
  • x : save and close
  • 2g.txt : input filename

Author

Stewart Schatz

Career: Principal CNC Consultant for Syntax Systems Limited specializing Oracle JD Edwards EnterpriseOne and the technology that supports it. Side Hustle: Owner/Operator of E1Tips.com Location: Lancaster, PA USA  What I like to do: Invest in Family, Explore Technology, Lead Teams, Share Knowledge/Experience, Hunt, Hike, etc.
Happy
Happy
0
Sad
Sad
0
Excited
Excited
0
Sleepy
Sleepy
0
Angry
Angry
0
Surprise
Surprise
0

Average Rating

5 Star
0%
4 Star
0%
3 Star
0%
2 Star
0%
1 Star
0%

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Previous post Windows 2003 Firewall Rules Allow UNC Access To Shared Folders
Next post How To Kill Zombies The Easy Way