You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Bash脚本从多记录文本文件提取指定属性值生成CSV

问题描述

我有一个结构如下的文本文件:

Record 1
property1: some_number1
property2: some_number2
property3: some_number3
...
property20: some_number

Record 2
property1: some_other_number1
property2: some_other_number2
property3: some_other_number3
...
property20: some_other_number
...
...
...
Record 350
property1: more_numbers1
property2: more_numbers2
property3: more_numbers3
...
property20: some_other_number

(其中...代表更多属性或记录)

我需要写一个Bash脚本,输入记录编号和目标属性名,提取对应属性的值并保存到.csv文件。比如输入记录编号2和属性property2,输出的CSV内容应为:

Record, property2
2,some_other_number2 

我试过逐行读取文件,先找指定的Record X字符串,再往后找对应属性的行,但没成功。

解决方案

方法1:用awk实现(推荐)

awk天生适合处理这种按区块划分的文本,能精准定位目标记录块并提取属性值,效率也高:

#!/bin/bash

# 读取用户输入的记录编号和属性名
read -p "输入记录编号: " record_num
read -p "输入目标属性名: " target_prop

# 替换成你的实际数据文件路径
source_file="your_records.txt"
output_file="result.csv"

# 核心awk处理逻辑
awk -v rec="$record_num" -v prop="$target_prop" '
BEGIN {
    # 先打印CSV表头
    print "Record, " prop
}
# 匹配到目标记录的起始行时,标记进入目标块
$1 == "Record" && $2 == rec {
    in_target_record = 1
}
# 在目标记录块内,匹配目标属性行
in_target_record && $1 == prop {
    # 提取冒号后面的属性值(跳过冒号和空格)
    value = substr($0, index($0, ":") + 2)
    print rec ", " value
    # 找到结果后直接退出,不用继续遍历
    exit
}
# 遇到空行,说明当前记录块结束,取消标记
/^$/ {
    in_target_record = 0
}
' "$source_file" > "$output_file"

echo "结果已保存到 $output_file"

使用步骤:

  1. 将your_records.txt替换为你的实际数据文件路径
  2. 给脚本加执行权限:chmod +x extract_record.sh
  3. 运行脚本,按提示输入记录编号和属性名即可

方法2:用grep+sed组合实现

如果更习惯用基础命令工具,也可以用grep定位记录块,再用sed提取属性:

#!/bin/bash

read -p "输入记录编号: " record_num
read -p "输入目标属性名: " target_prop

source_file="your_records.txt"
output_file="result.csv"

# 写入CSV表头
echo "Record, $target_prop" > "$output_file"

# 提取目标记录的后20行(对应20个属性),再筛选目标属性行并格式化
grep -A20 "Record $record_num" "$source_file" | grep "$target_prop" | sed -E "s/^$target_prop: (.*)/$record_num, \1/" >> "$output_file"

echo "结果已保存到 $output_file"

注意:这里的-A20表示取匹配行之后的20行,如果你的属性数量不是20,需要调整这个数字。

为什么你之前的逐行读取方法失败?

大概率是没处理好记录块的边界——找到Record X后,没有正确识别空行作为记录块的结束标记,导致后续遍历到其他记录的属性时误匹配。上面的awk方法通过in_target_record标记精准控制只在目标记录块内查找,完美解决了这个问题。

内容的提问来源于stack exchange,提问作者anon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 16:20:37