0
点赞
收藏
分享

微信扫一扫

Linux 学习之路--工具篇--yum

zmhc 04-01 23:00 阅读 1


请阅读【嵌入式开发学习必备专栏 】


文章目录

将一个文件从第 N 行开始分成两个文件

要在 shell 中将一个文件从第 n 行开始分成两个文件,可以使用 headtail 命令。下面是一个示例脚本,该脚本接收三个参数:源文件名、行号 n 和目标文件前缀。脚本将创建两个文件:一个包含开始到第 n-1 行的内容,另一个包含第 n 行到文件末尾的内容。

#!/bin/bash
# 参数检查
if [ "$#" -ne 3 ]; then
    echo "Usage: $0 <source file> <line number> <destination prefix>"
    exit 1
fi
# 输入参数
source_file=$1
line_number=$2
dest_prefix=$3
# 计算源文件的总行数
total_lines=$(wc -l < "$source_file")
# 验证行号是否有效
if [ "$line_number" -lt 1 ] || [ "$line_number" -gt "$total_lines" ]; then
    echo "Error: Line number is out of range."
    exit 1
fi
# 从开始到第 n-1 行
head -n $((line_number - 1)) "$source_file" > "${dest_prefix}_part1.txt"
# 从第 n 行到文件末尾
tail -n +$line_number "$source_file" > "${dest_prefix}_part2.txt"
echo "File has been split into '${dest_prefix}_part1.txt' and '${dest_prefix}_part2.txt'."

将此脚本保存为 split_file.sh 并给它执行权限:

chmod +x split_file.sh

然后使用如下命令执行脚本:

./split_file.sh inputfile.txt 10 outputfile

这里 inputfile.txt 是需要分割的源文件,10 是行号 noutputfile 是目标文件的前缀。执行这个脚本将会创建 outputfile_part1.txtoutputfile_part2.txt 两个文件,分别包含源文件的第1行到第9行和第10行到末尾的内容。

如果想根据多个行号将文件分割成多个部分,可以使用下面的脚本来实现。假设 传入的行号已经按照从小到大的顺序排列,并且不包括文件的最后一行(因为 tail 可以用来处理到文件末尾的情况):

#!/bin/bash
# 检查参数数量
if [ $# -lt 2 ]; then
    echo "Usage: $0 <source file> <line number 1> [line number 2] ... [line number N]"
    exit 1
fi
# 获取源文件名和行号列表
source_file=$1
shift
line_numbers=("$@")
# 记录上一个行号,初始化为文件开始
last_line_num=0
# 文件分割标识
file_index=1
# 遍历所有行号,分割文件
for line_num in "${line_numbers[@]}"; do
    # 计算行的范围
    start_line=$((last_line_num + 1))
    end_line=$((line_num - 1))
    
    # 切割文件的对应行范围
    if [ $start_line -le $end_line ]; then
        sed -n "${start_line},${end_line}p;${end_line}q" "$source_file" > "${source_file}_part${file_index}"
    else
        # 如果两个行号相同或逆序,则创建一个空文件
        touch "${source_file}_part${file_index}"
    fi
    
    # 更新最后行号为当前行号
    last_line_num=$line_num
    ((file_index++))
done
# 最后,从最后一个行号到文件末尾
tail -n +$((last_line_num + 1)) "$source_file" > "${source_file}_part${file_index}"

要运行此脚本,请将其保存到文件(例如 split_by_lines.sh),然后使其可执行:

chmod +x split_by_lines.sh

之后, 可以像这样调用它:

./split_by_lines.sh yourfile.txt 10 20 30

上述命令将 yourfile.txt 分割为四个部分:

  • yourfile.txt_part1 包含行 1 到 9
  • yourfile.txt_part2 包含行 10 到 19
  • yourfile.txt_part3 包含行 20 到 29
  • yourfile.txt_part4 包含行 30 到文件末尾
    请注意, 应该确保传入的行号是有效的,且按照升序排列。如果两个连续的行号相同或者是逆序的,脚本将为这部分创建一个空文件
举报

相关推荐

0 条评论