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

用Awk/Perl提取首列内容换行;Bash下批量复制数字下划线前缀至后续行

Hey there! Let's break down your two text processing tasks with straightforward, tested solutions using Awk, Perl, and Bash tools—perfect for handling table data in the shell.

1. Extract the First Column of a Table and Print Each Line

Whether you prefer Awk or Perl, both tools make extracting the first column a breeze. Here are the go-to commands:

Using Awk

Awk is built for columnar data processing. By default, it splits lines on whitespace (spaces/tabs), so $1 refers to the first field.

awk '{print $1}' your_table.txt

If your table uses a different delimiter (like commas or pipes), use the -F flag to specify it. For example, comma-separated values:

awk -F',' '{print $1}' your_table.csv

Using Perl

Perl's -a flag auto-splits each line into an array @F, where $F[0] is the first element. The -l flag handles newline characters cleanly:

perl -lane 'print $F[0]' your_table.txt

Same as Awk, you can set a custom delimiter with -F if needed:

perl -F',' -lane 'print $F[0]' your_table.csv

2. Repeat Header Rows (Numbers + Underscores) for Subsequent Lines

For this task, Awk is ideal because it lets you track the last matching header and apply it to all lines until the next header comes along. Let's say your input looks like this:

123_sales
Q1_revenue
Q2_expenses
456_inventory
stock_levels
supplier_data

We want to append the nearest header (like 123_sales) to every line that follows it, until we hit the next header (456_inventory). Here's the command:

awk '/^[0-9_]+$/ {
    current_header = $0
    print  # Remove this line if you don't want to keep the original header row
    next
}
{
    print current_header, $0
}' your_input.txt

What this does:

  • When a line matches the pattern ^[0-9_]+$ (only numbers and underscores), we store it in current_header and print it (optional—remove the print if you don't need the original header line).
  • For all other lines, we print the stored current_header followed by the line content.

Example Output:

123_sales
123_sales Q1_revenue
123_sales Q2_expenses
456_inventory
456_inventory stock_levels
456_inventory supplier_data

If you want to merge the header and line into a single field (e.g., with a separator like |), just adjust the print statement:

print current_header "|" $0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 06:23:17