列提取脚本怎么做?

wen 实用脚本 45

本文目录导读:

列提取脚本怎么做?

  1. 使用 awk(处理文本/csv文件)
  2. 使用 cut 命令(简单快速)
  3. Python 脚本(最灵活)
  4. Excel/CSV 文件处理(pandas)
  5. 批量处理多个文件
  6. 选择建议:

我来为你介绍几种常见的“列提取”脚本方法,针对不同的数据格式和需求场景:

使用 awk(处理文本/csv文件)

# 提取第1、3、5列
awk '{print $1, $3, $5}' input.txt
# 指定分隔符(如逗号CSV)
awk -F',' '{print $1, $3}' input.csv
# 提取某列出现的行
awk '{if($2 > 100) print $0}' data.txt

使用 cut 命令(简单快速)

# 提取第1、3、5字符列
cut -c1,3,5 input.txt
# 按分隔符提取列(逗号分隔)
cut -d',' -f1,3 input.csv
# 提取范围列(第2到第5列)
cut -f2-5 input.txt

Python 脚本(最灵活)

# 基础版:从CSV提取指定列
import csv
def extract_columns(input_file, output_file, columns=[0,2,4]):
    with open(input_file, 'r') as f_in, open(output_file, 'w') as f_out:
        reader = csv.reader(f_in)
        writer = csv.writer(f_out)
        for row in reader:
            selected = [row[i] for i in columns if i < len(row)]
            writer.writerow(selected)
# 使用
extract_columns('data.csv', 'output.csv', [0, 1, 3])
# 进阶版:支持多种格式
def extract_columns_advanced(file_path, columns, delimiter='\t', has_header=False):
    """
    file_path: 文件路径
    columns: 要提取的列索引列表(从0开始)
    delimiter: 分隔符
    has_header: 是否有表头
    """
    with open(file_path, 'r') as f:
        lines = f.readlines()
    # 处理表头
    if has_header:
        headers = lines[0].strip().split(delimiter)
        selected_headers = [headers[i] for i in columns if i < len(headers)]
        print("提取的列:", selected_headers)
        lines = lines[1:]
    # 提取数据
    for line in lines:
        if not line.strip():
            continue
        parts = line.strip().split(delimiter)
        selected = [parts[i] for i in columns if i < len(parts)]
        print(delimiter.join(selected))
# 使用
extract_columns_advanced('data.tsv', [0, 2, 4], delimiter='\t')

Excel/CSV 文件处理(pandas)

import pandas as pd
# 读取Excel或CSV
df = pd.read_csv('data.csv')  # 或 pd.read_excel('data.xlsx')
# 按列名提取
result = df[['Name', 'Age', 'Score']]
# 按列索引提取
result = df.iloc[:, [0, 2, 4]]  # 第0、2、4列
# 按条件筛选列
import re
cols = [col for col in df.columns if re.match(r'^temp_\d+', col)]
result = df[cols]
# 保存结果
result.to_csv('output.csv', index=False)

批量处理多个文件

#!/bin/bash
# 批量提取目录下所有csv的第1、3列
for file in *.csv; do
    output="extracted_${file}"
    cut -d',' -f1,3 "$file" > "$output"
    echo "处理完成: $file -> $output"
done

选择建议:

  • 小文件、简单文本:用 awkcut
  • 复杂CSV/Excel:用 Python + pandas
  • 需要条件筛选:用 Python 或 awk
  • Linux环境:awk 最简洁
  • Windows环境:PowerShell 或 Python

如果你有具体的文件格式或需求,可以告诉我,我帮你写更精准的脚本。

抱歉,评论功能暂时关闭!