我需要用零填充 csv 檔案的第 6 列,但是當我嘗試使用以下命令時,它只是將實際值替換為 0000。
awk -F',' -v OFS=',' '{$6 = sprintf("d", $6); print}' $Input
輸入:
"xx","x","xxxxxx","xxx","xx","123","xxxxxxxxx","xxxxx"
"xx","x","xxxxxx","xxx","xx" ,"23","xxxxxxxxx","xxxxx"
"xx","x","xxxxxx","xxx","xx","3","xxxxxxxxx","xxxxx"
"xx","x" ,"xxxxxx","xxx","xx","4123","xxxxxxxxx","xxxxx"
輸出:
"xx","x","xxxxxx","xxx","xx","0123","xxxxxxxxx","xxxxx"
"xx","x","xxxxxx","xxx","xx" ,"0023","xxxxxxxxx","xxxxx"
"xx","x","xxxxxx","xxx","xx","0003","xxxxxxxxx","xxxxx"
"xx","x" ,"xxxxxx","xxx","xx","4123","xxxxxxxxx","xxxxx"
uj5u.com熱心網友回復:
您可以將其awk與自定義欄位分隔符一起使用",":
awk 'BEGIN {FS=OFS="\",\""} {$6 = sprintf("d", $6)} 1' file
"xx","x","xxxxxx","xxx","xx","0123","xxxxxxxxx","xxxxx"
"xx","x","xxxxxx","xxx","xx","0023","xxxxxxxxx","xxxxx"
"xx","x","xxxxxx","xxx","xx","0003","xxxxxxxxx","xxxxx"
"xx","x","xxxxxx","xxx","xx","4123","xxxxxxxxx","xxxxx"
uj5u.com熱心網友回復:
一些非 awk 的方法來做到這一點:
bash v5.1 包含一個可以啟用的 CSV 命令:
BASH_LOADABLES_PATH=${BASH/bin/lib}
enable -f csv csv
while IFS= read -r line; do
csv -a row "$line"
printf -v "row[5]" 'd' "${row[5]}"
printf '"%s"\n' "${row[@]}" | paste -sd,
done < file
紅寶石
ruby -rcsv -e '
CSV.foreach(ARGV.shift) {|row|
row[5] = row[5].rjust(4, "0")
puts CSV.generate_line(row, force_quotes: true)
}
' file
帶有文本的 Perl::CSV
perl -MText::CSV=csv -e '
$input = csv(in => shift @ARGV);
@padded = map {$_->[5] = sprintf "d", $_->[5]; $_} @$input;
csv(in => \@padded, always_quote => 1)
' file
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/341202.html
