用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.
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
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 incurrent_headerand print it (optional—remove theprintif you don't need the original header line). - For all other lines, we print the stored
current_headerfollowed 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

