Shell脚本实现为.lvm文件指定行列写入标识值的问题求助
Hey there! Let's get your scripts sorted to produce that desired output. I'll walk through fixing each script step by step, since your current code has a few syntax issues and missing logic.
First Script: Process .lvm Files & Add End-of-File Marker
Your first script needs to: skip the file header (up to the X_Value line), add the filename as the first column, set column 18 (now column 19 after adding the filename) to 0 for all lines except the last one, which gets 500. Here's the corrected version:
#!/bin/sh # Iterate over all .lvm files in the directory passed as argument for file in "$1/"*.lvm; do # Extract just the filename (without the full path) filename=$(basename "$file") # Find the line number where "X_Value" appears (end of header) header_line=$(awk '/X_Value/{ print NR; exit }' "$file") # Calculate the first line of actual data (right after the header) start_line=$((header_line + 1)) # Use awk to process the file: # 1. Skip header lines before start_line # 2. Prepend the filename as the first column # 3. Set the appropriate value for the marker column (originally column 18, now 19) awk -v start="$start_line" -v fname="$filename" ' BEGIN {OFS = "\t"} # Set output field separator to tab NR < start {next} # Skip all header lines { # Add filename as the first field $0 = fname "\t" $0 # Check if this is the last line of the file if (NR != END) { $(19) = 0 # Non-last lines get 0 in the marker column } else { $(19) = 500 # Last line gets 500 } print $0 } ' "$file" done
Key fixes here:
- Removed the unnecessary
clearcommand and fixed syntax issues - Properly extracts the filename to prepend to each line
- Correctly skips header lines using the
X_Valuemarker - Adjusted the target column to 19 (since we added a new first column for the filename)
- Uses valid awk logic to set the marker value based on whether the line is the last one in the file
Second Script: Extract Desired Columns
Your second script needs to output the 5 original columns plus the new marker column. Since we added the filename as column 1, the original columns shift right by 1. Here's the updated script:
#!/bin/sh # Read input line by line, extract desired columns including the marker while read -r line; do awk -v OFS='\t' '{print $1, $2, $3, $8, $18, $19}' <<< "$line" sleep 1 # Keep your sleep if you need it for pacing/output done # Alternatively, for better performance (skip the while loop): # awk -v OFS='\t' '{print $1, $2, $3, $8, $18, $19}'
How to Run
Just use your existing pipeline setup:
./first_script.sh /path/to/your/lvm/files | ./second_script.sh
This will produce output matching your desired format, with each file's lines ending in 0 except the final line which ends in 500.
内容的提问来源于stack exchange,提问作者Jovel

