마지막 필드의 출력을 정렬하는 방법

마지막 필드의 출력을 정렬하는 방법

배쉬 스크립트

for i in $script_name
do
  echo -en "running the script - $i\t - "
  exec 3>&1 4>&2
  var=$( { time /tmp/scripts/$i 1>&3 2>&4; } 2>&1)  # Captures time only
  exec 3>&- 4>&-

  echo "$var"
done

다음을 인쇄하세요:

running the script - Verify_disk.bash -       1.42
running the script - Verify_yum_list.bash - 10.49
running the script - Verify_size.bash -   2.93
running the script - Verify_mem_size.bash -       0.71
running the script - Verify_disk_size.bash -      2.41
running the script - Verify_wdisk.bash -        1.63
running the script - Verify_cpu.bash - 0.74

$var는 이 모든 출력을 인쇄하는 변수이므로 출력을 정렬하고 싶습니다.

그럼 이렇게 되겠죠

running the script - Verify_disk.bash        -   1.42
running the script - Verify_yum_list.bash    -   10.49
running the script - Verify_size.bash        -   2.93
running the script - Verify_mem_size.bash    -   0.71
running the script - Verify_disk_size.bash   -   2.41
running the script - Verify_wdisk.bash       -   1.63
running the script - Verify_cpu.bash         -   0.74

마지막 필드를 정렬하기 위해 $var에 추가로 변경해야 할 사항은 무엇입니까?

답변1

사전 루프를 수행하여 가장 긴 파일 이름을 계산한 다음 이를 간격 매개변수로 사용합니다.

longest=0
for file in *.bash
do
  [ "${#file}" -gt "$longest" ] && longest=${#file}
done

# ... for your execution loop
printf "running the script - %${longest}s\t- "
printf "%s\n" "$var"

모든 스크립트가 와일드카드에 포함되어 있다고 가정합니다 *.bash. 필요에 따라 조정하세요. 초기 루프는 필요한 너비를 계산합니다. printf이 변수는 처음에 루프의 각 반복에 대한 스크립트 필드의 너비 형식을 지정하는 데 사용됩니다 for.

답변2

루프의 초기 반복에서는 다음 변수의 너비를 알 수 없기 때문에 스크립트 내에서 적절한 형식을 지정할 수 없다고 생각합니다. 2단계 프로세스는 어떻습니까?

나는 또한 시간 값의 출력을 오른쪽으로 정렬하는 자유(개인 선호도)를 취했습니다.

샘플 입력을 파일(동적으로 생성할 수 없음)에 저장한 후 제안하는 내용은 다음과 같습니다.

cat yael | awk -F'-' '{printf "%s - %-30s - % 6.2f\n",$1, $2, $3}' 
running the script  -  Verify_disk.bash              -   1.42
running the script  -  Verify_yum_list.bash          -  10.49
running the script  -  Verify_size.bash              -   2.93
running the script  -  Verify_mem_size.bash          -   0.71
running the script  -  Verify_disk_size.bash         -   2.41
running the script  -  Verify_wdisk.bash             -   1.63
running the script  -  Verify_cpu.bash               -   0.74

따라서 내 awk를 통해 스크립트의 출력을 파이프한다면...

관련 정보