Shell 腳本輸出格式

Shell 腳本輸出格式

我有一個以下格式的文件 -

root            0       system          0  
                        bin             2
                        sys             3
                        security        7
                        cron            8
                        audit           10
                        lp              11
daemon          1       staff           1  
bin             2       bin             2  
                        sys             3
                        adm             4
sys             3       sys             3  

並想使用 shell 腳本將其轉換為新的文件格式 -

root            system,bin,sys,security,cron,audit,lp
daemon          staff
bin             bin,sys,adm
sys             sys

答案1

開箱即用的awk解決方案:

awk 'NF==4 && NR>1 {printf "\n" ; } 
     NF==4 { printf "%-10s %s",$1,$3} 
     NF==2 { printf ",%s",$1} 
     END   { printf "\n" ; } '

在哪裡

  • NF是字段數(列數),
  • NR是記錄數(行號),
  • 各種條件選擇要列印的內容,
  • printf不列印尾隨新行。

答案2

perl -lane '
   if ( @F == 4 ) {                 # num fields are 4
      print $result if $. > 1;      # in case we"re not @ BOF, show result
      $result = join "\t", @F[0,2]; # initialize result
   } else {
      $result .= ",$F[0]";          # append result
   }
   eof && print $result;            # on the last line, show result
' filename

答案3

perl -0pe 's/\h+\d+\h*\n\h+/,/g;  s/\h+\d+//g' ex
  • 第一個替換替換數字,然後\n...spaces,
  • 第二次替換刪除其他數字。

相關內容