Site icon moneyslow.com

shell脚本truncate命令利用关键词对文本文件进行截断

shell下利用awk sort uniq 对nginx日志进行统计分析

shell下利用awk sort uniq 对nginx日志进行统计分析

先看看truncate的基本参数:

Mandatory arguments to long options are mandatory for short options too.
-c, --no-create do not create any files
-o, --io-blocks treat SIZE as number of IO blocks instead of bytes
-r, --reference=RFILE base size on RFILE
-s, --size=SIZE set or adjust the file size by SIZE bytes
--help display this help and exit
--version output version information and exit

使用truncate清除文件的内容
truncate -s 0 file
这非常有用,例如用于清除日志文件。这比手动删除文件并触摸新文件要好。截断过程基本上删除了文件的所有内容。它不会删除文件本身,但会将其作为零字节文件留在磁盘上。
du -sh /var/log/syslog
616K /var/log/syslog
truncate -s 0 /var/log/syslog
如果我们再次检查文件大小,它应该是0字节。
du -sh /var/log/syslog
0 /var/log/syslog
请注意,truncate命令将保留文件权限和所有权。您可以使用ls-lh命令进行确认:
ls -lh /var/log/syslog
-rw-r----- 1 syslog adm 0 Mar 17 18:34 /var/log/syslog
将文件truncate为特定大小的步骤
下面的示例将文件截断为100字节大小。
touch file.txt
ls -lh file.txt
-rw-r--r-- 1 root root 0 Mar 17 18:39 file.txt
truncate -s 100 file.txt
现在检查文件大小:
ls-lh file.txt
-rw-r--r--1根根目录100 Mar 17 18:40 file.txt
要将文件截断为100 KB,请执行以下操作:
truncate -s 100K file.txt
ls -lh file.txt
-rw-r--r-- 1 root root 100K Mar 17 18:41 file.txt
根据需要,可使用M、G、T、P、E、Z和Y代替“K”。
使用truncate扩展文件大小
您还可以将文件大小从当前扩展到所需的状态。使用大小为+的选项-s。
$ touch file.txt
$ truncate -s 100K file.txt
$ ls -lh file.txt
-rw-r--r-- 1 jmutai wheel 100K Mar 18 13:12 file.txt
$ truncate -s +200K file.txt
$ ls -lh file.txt
-rw-r--r-- 1 jmutai wheel 300K Mar 18 13:12 file.txt
这将通过添加额外的200K将文件大小从100K扩展到300K。
使用truncate减少文件大小
假设您有一个500K文件,并希望将其缩小到250K。您将使用-s选项并指定-in大小。例如
$ ls -lh file.txt -rw-r--r-- 1 jmutai wheel 500K Mar 18 13:15 file.txt
$ truncate -s -250K file.txt
$ ls -lh file.txt
-rw-r--r-- 1 jmutai wheel 250K Mar 18 13:15 file.txt
您可以看到当前大小已更改为250K。Linux truncate命令,将文件更改为指定大小。

利用上面的知识,如果想通过一个关键词把一个文本文件进行截断,那就可以先找出关键词的偏移量,再利用truncate只取偏移量的部分

文本文件

上图中以3为关键词,将文件截断为到3截止

截断后的文本文件

附上shell脚本:

#!/bin/bash
# 检查参数是否正确
if [ $# -ne 2 ]; then
            echo "Usage: $0 keyword filename"
                exit 1
        fi
# 保存关键词和文件名
keyword=$1
filename=$2
# 搜索关键词在文件中的位置
position=$(grep -b -o $keyword $filename | cut -d: -f1)
# 如果没有找到关键词,则退出
if [ -z "$position" ]; then
    echo "Keyword not found in file"
    exit 1
fi
# 把文件截断到关键词位置
truncate -s $position $filename
echo "File truncated at position $position"
Exit mobile version