Views:
268,690β
Votes: 7β
Tags:
command-line
bash
files
Link:
π See Original Answer on Ask Ubuntu β§ π
URL:
https://askubuntu.com/q/1017769
Title:
How to clear text in a file?
ID:
/2018/03/20/How-to-clear-text-in-a-file_
Created:
March 20, 2018
Edited: June 12, 2020
Upload:
September 15, 2024
Layout: post
TOC:
false
Navigation: false
Copy to clipboard: false
Not the shortest answer butβ¦
This answer is based on another from Super User. Although not the shortest bash command, truncate
is the most readable for average newbies:
$ echo Hello > Hello.txt
$ echo World! >> Hello.txt
$ cat Hello.txt
Hello
World!
$ truncate -s 0 Hello.txt
$ ll Hello.txt
-rw-rw-r-- 1 rick rick 0 Mar 20 17:32 Hello.txt
Parameters used with truncate
command here:
- β-sβ set the size
- β0β size will be zero
Clear everything except first 10,000 bytes
An advantage of truncate
is you can specify how much to keep, not just zero:
$ truncate -s 10000 Hello.txt
β¦ will truncate everything after the first 10,000 bytes. This could be useful if a program went crazy and dumped many Megabytes of data into a small log file:
- Run the
truncate
command for a reasonable larger normal size of 10K - Open the file with your text editor and press End
-
Highlight and PgUp to delete the remaining bytes that donβt belong (usually recognizable by ASCII garbage characters).