基于CSV第三列批量编辑第二列并处理_f_行前缀
Here's the modified awk command that combines both your requirements: removing the prefix from the second column using the third column's value, and adding the "f. " prefix when the first column contains "f":
BEGIN{FS=OFS=","} NR==1 && NF>2 { # Capture the X value from the third column of the first row s = $3 # Escape regex special characters in X to ensure literal matching gsub(/[.*+?^$()|[\]\\]/, "\\&", s) } { # Remove leading X (and any following whitespace) from the second column sub("^" s "[[:space:]]+", "", $2) # Add "f. " prefix to the second column if first column has "_f_" if (index($1, "_f_") != 0) { $2 = "f. " $2 } # Print the modified line print }
How it works:
- Set CSV field separators:
FS=OFS=","ensures we correctly split and rejoin columns using commas, preserving the CSV structure. - Capture the shared X value: On the first row (
NR==1), we store the third column's value in variables(this is your consistent X value). We escape regex special characters insto avoid unintended matches if X contains dots, asterisks, or other regex-specific symbols. - Clean up the second column: We remove the leading X value (and any trailing whitespace) from the second column using
sub(). - Add the "f. " prefix: If the first column (filename) contains "f", we prepend "f. " to the cleaned-up second column.
- Output the modified row: The final
printstatement writes the updated line to the output.
To use this command, replace $pathToCSV with your actual file path (without the .csv suffix):
# Run with a separate output file (safer for testing) awk 'BEGIN{FS=OFS=","} NR==1 && NF>2 {s=$3; gsub(/[.*+?^$()|[\]\\]/, "\\&", s)} {sub("^" s "[[:space:]]+", "", $2); if (index($1, "_f_") !=0) $2="f. "$2} 1' "$pathToCSV.csv" > output.csv
If you want to edit the file in-place (like sed -i), you can use GNU awk's in-place editing (version 4.1+):
awk -i inplace 'BEGIN{FS=OFS=","} NR==1 && NF>2 {s=$3; gsub(/[.*+?^$()|[\]\\]/, "\\&", s)} {sub("^" s "[[:space:]]+", "", $2); if (index($1, "_f_") !=0) $2="f. "$2} 1' "$pathToCSV.csv"
内容的提问来源于stack exchange,提问作者Kay Gee
相关产品推荐
相关产品推荐

