简体   繁体   English

(Linux)将变量格式化为列printf

[英](Linux) Formatting variables into columns printf

I'm trying to show a file name, size and type in 3 columns. 我正在尝试在3列中显示文件名,大小和类型。 The data just isn't showing correctly and I just can't see why. 数据只是无法正确显示,我只是看不到为什么。

Here's my code: 这是我的代码:

    fileName=$(ls -a ~/dirname)
    fileSize=$(find ~/dirname/* -printf '%s\n';)
    fileType=$(find ~/dirname/* | xargs file |  awk '{print $3}')

    printf " ----------------------------------------------------------\n"
    printf "%15s %15s %15s\n" "Name" "Size" "Type"
    printf " ----------------------------------------------------------\n"
    printf "%15s  %15s  %15s\n" "$fileName" "$fileSize" "$fileType"


The output is showing like: (Output as an image just to avoid stackoverflows formatting) 输出显示为:(输出为图像只是为了避免stackoverflows格式化)

输出截图

Your variables each hold the information for all the files, but you're printing them at one time, not separating them. 每个变量都包含所有文件的信息,但是您要一次打印它们,而不是将它们分开。 Also, the order of files returned by find is not the same as the order of ls (it sorts them lexicographically). 另外, find返回的文件顺序与ls的顺序不同(按字母顺序对它们进行排序)。

You need to loop over the files and print each one on a different line: 您需要遍历文件并在不同的行上打印每个文件:

printf "%15s %15s %15s\n" "Name" "Size" "Type"
printf " ----------------------------------------------------------\n"
ls -a ~/dirname | while read -r fileName
do
    fileSize=$(stat --format=%s "$fileName")
    fileType=$(file "$fileName" | awk '{print $3}')
    printf "%15s  %15s  %15s\n" "$fileName" "$fileSize" "$fileType"
done

I solved it with a little bit of help from Barmar identifying what I was doing wrong: 在Barmar的一点帮助下,我找出了我做错的地方来解决了这个问题:

    for fileName in $(ls -a ~/dirname/*);
    do
            fileSize=$(stat --printf="%s" "$fileName")
            fileType=$(file "$fileName" | awk '{print $3}')
            printf "%15s  %15s  %15s\n" $(basename "$fileName") "$fileSize" "$fileType"
    done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM