- Как обрезать файлы до нулевого размера в Linux
- How to Truncate (Empty) Files in Linux
- В этом руководстве объясняется, как обрезать файлы до нулевого размера в системах Linux с помощью перенаправления оболочки и truncate команды.
- Shell Redirection
- truncate команда
- Очистить все файлы журнала
- Вывод
- How to Use Truncate Command in Linux
- Common truncate options
- Examples of truncate usage
- 1. Clear contents of a file with truncate
- 2. To truncate a file to a specific size
- 3. Extend file size with truncate
- 4. Reduce file size with truncate
- Conclusion
- Truncate Large Text File in UNIX / Linux
- Options #1: Shell Output Redirction
- Option #2: truncate Command
- Option #3: logrotate Utility
- Option #4: /dev/null
Как обрезать файлы до нулевого размера в Linux
How to Truncate (Empty) Files in Linux
В этом руководстве объясняется, как обрезать файлы до нулевого размера в системах Linux с помощью перенаправления оболочки и truncate команды.
В некоторых ситуациях может потребоваться усечь (очистить) существующий файл до нулевой длины. Проще говоря, усечение файла означает удаление содержимого файла без удаления файла.
Усечение файла происходит намного быстрее и проще, чем удаление файла , его воссоздание и установка правильных прав доступа и владельца . Кроме того, если файл открывается процессом, удаление файла может привести к сбою в работе программы, которая его использует.
Shell Redirection
Самый простой и наиболее используемый метод для усечения файлов — это использование > — оператора перенаправления оболочки.
Общий формат для усечения файлов с использованием перенаправления:
- В : средстве толстой кишки true и не производит никакого вывода.
- Оператор > перенаправления перенаправляет вывод предыдущей команды в указанный файл.
- filename , файл, который вы хотите усечь.
Если файл существует , он будет обрезан до нуля. В противном случае файл будет создан.
Вместо : можно также использовать другую команду, которая не выдает никаких результатов.
Вот пример использования cat команды для вывода содержимого /dev/null устройства, которое возвращает только символ конца файла:
Еще одна команда, которая может быть использована echo . -n Опция говорит echo не для добавления новой строки:
В большинстве современных оболочек, таких как Bash или Zsh, вы можете опустить команду перед символом перенаправления и использовать:
Чтобы иметь возможность обрезать файл, вам необходимо иметь права на запись в файл. Обычно вы бы использовали sudo для этого, но привилегии суперпользователя не применяются к перенаправлению. Вот пример:
Есть несколько решений, которые позволяют перенаправлять с sudo . Первый вариант может запустить новую оболочку с помощью sudo и выполнить команду внутри этой оболочки, используя -c флаг:
Другой вариант — передать вывод в tee команду, повысить tee привилегии sudo и записать пустой вывод в заданный файл:
truncate команда
truncate утилита командной строки, которая позволяет уменьшить или расширить размер файла до заданного размера.
Общий синтаксис для усечения файлов до нулевого размера с помощью truncate команды, выглядит следующим образом:
Например, чтобы очистить журнал доступа Nginx, вы должны использовать:
Очистить все файлы журнала
Со временем ваш диск может загромождаться большим количеством больших файлов журнала, занимающих много места на диске.
Следующая команда очистит файлы, заканчивающиеся на «.log» в /var/log каталоге:
Лучшим вариантом будет вращение, сжатие и удаление файлов журналов с помощью logrotate инструмента.
Вывод
Чтобы обрезать файл в Linux, используйте оператор перенаправления, > за которым следует имя файла.
Источник
How to Use Truncate Command in Linux
Welcome to our tutorial on how to use truncate command in Linux. The Linux truncate command is often used to shrink or extend the size of each FILE to the specified size. The final size of the file depends on the initial. If a FILE (for example archive or log files) is larger than the specified size, the extra data is lost, but if a FILE is shorter, it is extended and the extended part (hole) reads as zero bytes.
The commands shown were tested on CentOS 7 machine and Ubuntu 16.04 server. Most Linux distributions ship with truncate command. If your system doesn’t have a truncate command, for Ubuntu/ Debian system, it is provided by the coreutils package.
If not installed, use:
Common truncate options
When using truncate, the SIZE argument has to be an integer and optional unit (example: 10K is 10*1024). The Units as used are K, M, G, T, P, E, Z, Y (powers of 1024) or KB, MB. (as powers of 1000).
The SIZE argument may also be prefixed by one of the following modifying characters: ‘+‘ extend by, ‘—‘ reduce by, ‘ ‘ at least, ‘/‘ round down to multiple of, ‘%‘ round up to multiple of.
Examples of truncate usage
Below is the most common usage examples of the truncate command.
1. Clear contents of a file with truncate
This is useful e.g for log clearing files. This is better than manually deleting a file and maybe doing a touch for the new one. The truncation process basically removes all the contents of the file. It does not remove the file itself, but it leaves it on the disk as a zero byte file. As an example, let’s clear our /var/log/syslog to 0 bytes using truncate.
If we do a check again for the file size, it should be 0 bytes.
Note that truncate command will retain file permissions and ownership. You can confirm by using ls -lh commands:
2. To truncate a file to a specific size
The example below will truncate a file to 100 bytes in size.
Now check the file size:
# ls -lh file.txt
-rw-r—r— 1 root root 100 Mar 17 18:40 file.txt
To truncate a file to 100 KB:
The M, G, T, P, E, Z, and Y may be used in place of «K» as required.
3. Extend file size with truncate
You can as well extend the size of the file from current to the desired state. Use the option -s with a + in size.
This will extend the file size from 100K to 300K by adding extra 200K.
4. Reduce file size with truncate
Let’s say you have a 500K file and would like to shrink it to 250K. You’ll use the -s option with a — in size specified. E.g
You can see the current size changed to 250K.
Conclusion
This tutorial, hope helped you to understand Linux truncate command to alter file to specified size. Please share your suggestion and thoughts on the below comment section.
Источник
Truncate Large Text File in UNIX / Linux
H ow do I truncate or shrink large text file under UNIX / Linux operating systems?
There are various tools and methods to truncate
Tutorial details | |
---|---|
Difficulty level | Easy |
Root privileges | No |
Requirements | None |
Est. reading time | N/A |
large text files under UNIX / Linux operating systems as follows.
Options #1: Shell Output Redirction
Your can truncate text file and make the size to zero using redirection:
Please note that largefile.txt file is created if it doesn’t exist. And largefile.txt file is overwritten if it exists.
Option #2: truncate Command
Use the truncate command to shrink or extend the size of each FILE to the specified size:
The -s option is used to set SIZE to zero. See truncate command man page for more details:
man truncate
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
Option #3: logrotate Utility
logrotate command is designed to ease administration of systems that generate large numbers of log files. It allows automatic rotation, compression, removal, and mailing of log files. Each log file may be handled daily, weekly, monthly, or when it grows too large. See how to use logrotate command to rotates, compresses, and mails system logs stored in /var/log and other locations under UNIX / Linux oses.
Option #4: /dev/null
The null device /dev/null act as the black hole that discards all data written to it under Unix like operating system. You can use it as follows (hat tip to Philippe Petrinko):
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
Isn’t this more of a useless thing ? You lose all the data in the first two methods.
That is the point, you want to truncate file size. For example, some stupid app crate a log file due to some networking issue. Next you fixed the issue and you don’t want the data. So just truncate it.
I vote for Option#3. Can’t live without my logrotate.conf.
Option #4:
cp /dev/null toobig
Option #5:
cat /dev/null > toobig
Option #4:
cp /dev/null toobig
Option #5:
cat /dev/null > toobig
What does it mean to “rotate” log files?
“Please note that largefile.txt file is created if it doesn’t exist. And largefile.txt file is overwritten if it exits.”
Last word should be “exists” 🙂
Thanks for the heads up!
Truncating brings up a good time to remind users about sparse files. Before you try to truncate a file, make sure the file isn’t a sparse file. With sparse files, checking the size with ls -l will NOT give you the true file size. In fact, the file may look many times larger than it really is.
Always check the file with the command du to check the size of the file if there is any chance you may be dealing with a sparse file or if you aren’t sure.
@Dave: Yes, good to know/remember.
Nevertheless, [ls] can show blocks with [s / –size] option:
dd if=/dev/zero of=sparse bs=1 count=1 seek=1024k # let’s create a sparse-file
ls -ls sparse # show me your blocks
8 -rw-r—r— 1 user1 user1 1048577 feb 24 18:38 sparse
mentioning the ‘truncate’ command (as opposed to the library call), makes this Linux only (or other Unix-like without its own file utils, relying on GNU).
Please execute the below command in shell
it will truncate the file..
BTW Vivek, when will you add my options, as they are functional and relevant?
And yes, please modify “exits” into “exists” as Shoaibi pointed out, don’t you think?
Done. The faq has been updated.
I appreciate your feedback 🙂
Rama Akella points out the useless use of cat . The end goal is that you don’t want to change the inode of the file you wish to truncate to zero bytes. It’s functionally equivalent to run `> file` to accomplish this.
The truncate option that truncates the file in place saves me from the problem of having to dd the file to a temp file and write it back as I’m dealing with files in the hundreds of gigabytes. My outdated install of Gentoo doesn’t provide truncate in coreutils. I instead found the source from a FreeBSD machine and compiled it manually, not knowing at the time that the newer coreutils includes it.
Locate the truncate.c file in the FreeBSD world source tree. I found it here:
/usr/src/usr.bin/truncate/truncate.c
Copy this to your *nix system and compile it
gcc -o truncate truncate.c
Test it out in case the C libraries are too divergent before you use it.
For Gentoo I created an ebuild for those who are not able to update coreutils. I offer absolutely no warranties of my work or the files that I am using. I am redistributing the code without modification.
Источник