Awk
更改 csv 文件中的位置運算符
我一直在編輯一個 CSV 文件,所以我可以將它導入 postgres。此時我想在值為負“-”時將運算符從第5列更改為列的左側。當它是“+”時,我想刪除運算符。
目前 CSV:
10013534,2021-01-01,I,0090922002,000000000009102629+,000000000000000000-,000000000000000000-, 10013534,2021-01-01,I,0091000002,000000000063288833-,000000000000000000-,000000000000000000-, 10013534,2021-01-01,I,0091100005,000000000063288833-,000000000000000000-,000000000000000000-, 10013534,2021-01-01,I,0091110002,000000000063288833+,000000000000000000-,000000000000000000-, 10013534,2021-01-01,I,0099999995,000000008017897139-,000000000000000000-,000000000000000000-,
它應該怎麼看
10013534,2021-01-01,I,0090922002,000000000009102629,000000000000000000-,000000000000000000-, 10013534,2021-01-01,I,0091000002,-000000000063288833,000000000000000000-,000000000000000000-, 10013534,2021-01-01,I,0091100005,-000000000063288833,000000000000000000-,000000000000000000-, 10013534,2021-01-01,I,0091110002,000000000063288833,000000000000000000-,000000000000000000-, 10013534,2021-01-01,I,0099999995,-000000008017897139,000000000000000000-,000000000000000000-,
如有必要,可以刪除第 6 列和第 7 列
像這樣的東西:
awk -F "," '{sign=substr($5,length($5),1);$5=substr($5,0,length($5)-1); if(sign =="-"){$5="-"$5}; print}' ./mycsv
你可能想試試
function movesign (TMP) {IX = sub (/\+$/, "&", TMP) # create increment based on sign, so # to drop the plus signs return substr (TMP TMP, length(TMP) + IX, length(TMP) - IX) # by writing the string twice, and chop- # ping it off at the right position with # the right length, we get the desired result } /^#/ {pfx = substr($0, 8, 7) OFS substr($0, 32, 4) "-" substr($0, 30, 2) "-01" OFS substr($0, 36) # prepare prefix from header lines sub (/ *$/, "", pfx) # trim trailing spaces next } /^@/ {next } {gsub(/[+-]/, "&,") # massage the input line into the right shape sub(/[, ]*$/, "") gsub(/ */, ",") $1 = pfx OFS $1 # prepend the prefix $0 = $0 # and recalculate the fields $5 = movesign($5) # use function to taste # $6 = movesign($6) # $7 = movesign($7) } 1 ' OFS=, *.csv
它竊取了您迄今為止獲得的答案,但
.csv
在您的cwd
. 查看邏輯的評論,如果出現問題,請回來。