Perl

無法正確使用 Perl 連接在每次出現時附加一些內容 - 出現“在操作員預期的位置找到數組”錯誤

  • August 29, 2019

我有這樣的日誌行 -

/mnt/internal-app/logs/internal-app.log_2019-08-21.log.gz:2019-08-21 07:31:14,153 5458142 [XNIO-3 task-4] INFO  c.c.p.i.m.ws.FileManger [FileName.java:1838] - UUIDs in this bucket 8501792126581991569,8073766106536916628,4830289023695906800,6135982080116553120,8306484440313978157,9040948912536460872,8471856544054164043,5431263453539111247,7661719762428556576
/mnt/internal-app/logs/internal-app.log_2019-08-21.log.gz:2019-08-21 07:31:14,153 5458144 [XNIO-3 task-4] INFO  c.c.p.i.m.ws.FileManger [FileName.java:1838] - UUIDs in this bucket 6501792126581991569,8073766106536916628,4830289023695906800,6135982080116553120,8306484440313978157,9040948912536460872,8471856544054164043,5431263453539111247,7661719762428556576

我在 cat 的輸出中使用 perl 來獲取 UUID 並將它們中的每一個用雙引號括起來 -

cat eligible_uuids_final_app1.txt | perl -ne 'chomp;if(s/^.*UUIDs in this bucket //){@uuids=split(/,/); print "," , join ",",map{qq/"$_"/} @uuids; }'

得到 -

"9556896620363267700","7159125371810704365"

我還想將這些中的每一個都包含在第一個括號中。我不是 perl 專家,但能夠添加起始括號 -

cat eligible_uuids_final_app1.txt | perl -ne 'chomp;if(s/^.*UUIDs in this bucket //){@uuids=split(/,/); print "," , join ",(",map{qq/"$_"/} @uuids; }'

得到 -

("9556896620363267700",("7159125371810704365"

嘗試添加尾括號 -

cat eligible_uuids_final_app1.txt | perl -ne 'chomp;if(s/^.*UUIDs in this bucket //){@uuids=split(/,/); print "," , join ",(",map{qq/"$_"/}, join ,")" @uuids;  }'

出現語法錯誤 -

$ cat eligible_uuids_final_app1.txt | perl -ne 'chomp;if(s/^.*UUIDs in this bucket //){@uuids=split(/,/); print "," , join ",(",map{qq/"$_"/}, join ,")" @uuids;  }'
Array found where operator expected at -e line 1, near "")" "
   (Missing operator before  ?)
syntax error at -e line 1, near "},"
Execution of -e aborted due to compilation errors.

如果您希望每個元素都包含在括號和引號中,那麼您可以簡單地將它們添加到現有map塊中,即替換

map{qq/"$_"/}

經過

map{qq/"($_)"/}

您不想通過 - 加入數組元素,這(,將放在.(,``@uuids

您只需要(在加入之前和)之後列印一個。

例如,使用printf

$ perl -ne '
 chomp;
 if(s/^.*UUIDs in this bucket //) {
   @uuids=split(/,/);
   printf ",(%s)", join ",",map{qq/"$_"/} @uuids;
 }' eligible_uuids_final_app1.txt
,("8501792126581991569","8073766106536916628","4830289023695906800","6135982080116553120","8306484440313978157","9040948912536460872","8471856544054164043","5431263453539111247","7661719762428556576"),("6501792126581991569","8073766106536916628","4830289023695906800","6135982080116553120","8306484440313978157","9040948912536460872","8471856544054164043","5431263453539111247","7661719762428556576")

(為單行添加換行符以使其可讀)

我不確定您是要在其內部(...)還是外部使用前導逗號。我假設是前者。根據需要調整 printf 格式字元串。

您可能想要添加一個換行符(例如printf ",(%s)\n", ....;)。

引用自:https://unix.stackexchange.com/questions/537899