Shell-Script
在 CSV 文件中迭代 fieldA,其中 fieldB 具有指定值
我一直在嘗試設置一個腳本以在 gitbash 上執行,以處理一個 CSV 文件,以便每個具有特定值的記錄,最後一個欄位從空(
""
)更改為從 1 到 16 迭代的值。此外,更新值前面有一些文本。對於 CSV 文件中匹配的每條記錄,該欄位應如下所示
REP0001
,以 結尾REP0100
,然後重新開始。REP0001
這是輸入文本的範例:
"00:30:00","01:00:00","10/14/2014","RETURN","PASADENA","TX","12:30:00","sedan","","","corporate","CO01353" "01:00:00","01:30:00","10/14/2014","RENT OUT","HOUSTON","TX","00:30:00","sedan","","","personal",""
第一行範例,我不想更改,但仍將其包含在輸出中。第二行範例,我想將最後一個欄位從 更改為
""
以 開頭REP0001
並迭代到的值REP0100
,然後從 重新開始REP0001
。這是所需文本的範例:
"01:00:00","01:30:00","10/14/2014","RENT OUT","HOUSTON","TX","00:30:00","sedan","","","personal","REP0001"
我確實嘗試
sed
過,awk
但我不是腳本專家。我只能將找到具有我想要的值的記錄的部分放在一起,然後插入我想要的值。但我不知道如何做迭代魔術:awk 'BEGIN{FS=",";OFS=","} $4 ~ /"RENT OUT"/ {$12="\042""REP0001""\042"}1' Rentals.csv > output
有人可以指出我正確的方向嗎?該文件本身有大約 2000 行。
我相信這可以滿足您的要求:
$ awk 'BEGIN{FS=",";OFS=","} $4 ~ /"RENT OUT"/ {NF--;printf $0; x=x%100;x++; printf ",\"REP%04i\"\n",x;next} 1' rentals.csv "00:30:00","01:00:00","10/14/2014","RETURN","PASADENA","TX","12:30:00","sedan","","","corporate","CO01353" "01:00:00","01:30:00","10/14/2014","RENT OUT","HOUSTON","TX","00:30:00","sedan","","","personal","REP0001"
唯一改變的部分是這個命令:
$4 ~ /"RENT OUT"/ {NF--;printf $0; x=x%100;x++; printf ",\"REP%04i\"\n",x;next}
一次拿一件新作品:
NF--
這將從行中刪除(空白)最後一個欄位。
- `printf $0
這將列印該行(現在沒有最後一個欄位)。
x=x%100;x++
這將計數器取
x
模 100,然後將其遞增 1。這樣,計數器將從 1 循環到 100 並返回到 1。
printf ",\"REP%04i\"\n",x
這將列印我們新的包含計數器的最後一個欄位。
next
由於我們已經列印了這一行,我們告訴
awk
跳過其餘的命令並從該next
行重新開始。