Aix

更改格式並對齊計數

  • November 6, 2017

我想改變格式

來自:Sample.txt

  Count   Data
  1 C0263/Pre-approved Auto Load BC
  1 C0263/Pre-approved Auto Load BC Holders
  3 C0268/Pre-approved Auto Loan

至:Output.txt

  Data                                       Count
  C0263/Pre-approved Auto Load BC            1
  C0263/Pre-approved Auto BC Holders         1
  C0268/Pre-approved Auto Loan               3

awk解決方案:

awk 'NR==1{ printf "%4s%-44s%s\n",FS,$2,$1; next }
    { f1=$1; sub(/^ *[^ ]+ */,""); printf "%4s%-44s%s\n",FS,$0,f1 }' Sample.txt

輸出:

   Data                                        Count
   C0263/Pre-approved Auto Load BC             1
   C0263/Pre-approved Auto Load BC Holders     1
   C0268/Pre-approved Auto Loan                3

假設輸入數據在文件中datafile.txt並且您使用的是 POSIX shell,您可以說

sed -e 's/^\s*//' -e 's/\s\+/:/' datafile.txt | while IFS=':' read a b; do
 printf '%-30.29s%s\n' "$b" "$a"
done

sed命令將 (1) 刪除所有前導空格,然後 (2) 用冒號替換第一次出現的一個或多個空格;結果被傳送到一個while循環,該循環讀取由冒號分隔的兩個欄位,然後很好地列印它們。

如果輸入數據來自管道,則刪除datafile.txt參數並將其通過管道傳輸到sed.

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