0

GNU bash,版本 4.4.0
Ubuntu 16.04

我想列出目录中的所有文件并将它们打印到第二列,同时在第一列中打印文件的大小。例子

1024 test.jpg
1024 test.js
1024 test.css
1024 test.html  

我已经使用该ls命令完成了此操作,但 shellcheck 不喜欢它。例子:

In run.sh line 47:
ls "$localFiles" | tail -n +3 | awk '{ print $5,$9}' > "${tmp_input3}"
^-- SC2012: Use find instead of ls to better handle non-alphanumeric filenames.  

当我使用该find命令时,它还返回绝对路径。例子:

root@me ~ # mkdir -p /home/remove/test/directory
root@me ~ # cd /home/remove/test/directory && truncate -s 1k test.css test.js test.jpg test.html && cd
root@me ~ # find /home/remove/test/directory -type f -exec ls -ld {} \; | awk '{ print $5, $9 }'
1024 /home/remove/test/directory/test.jpg
1024 /home/remove/test/directory/test.js
1024 /home/remove/test/directory/test.css
1024 /home/remove/test/directory/test.html  

实现我的目标最有效的方法是什么。它可以是任何命令,只要 shellcheck 很酷,我很高兴。

4

3 回答 3

2

请试试:

find dir -maxdepth 1 -type f -printf "%s %f\n"
于 2019-09-29T00:49:56.170 回答
1

你可以使用如下所示的东西,

这是基本命令,

vagrant@ubuntu-bionic:~$ find ansible_scripts/ -follow -type f  -exec wc -c {} \;

输出,

vagrant@ubuntu-bionic:~$ find ansible_scripts/ -follow -type f  -exec wc -c {} \;
59 ansible_scripts/hosts
59 ansible_scripts/main.yml
266 ansible_scripts/roles/role1/tasks/main.yml
30 ansible_scripts/roles/role1/tasks/vars/var3.yaml
4 ansible_scripts/roles/role1/tasks/vars/var2.yaml
37 ansible_scripts/roles/role1/tasks/vars/var1.yaml

上面的命令用于描述我使用 find 命令得到的绝对路径。

以下是更新后的命令,您可以使用它来仅获取大小和文件名,但如果文件名相同,它可能会产生一些歧义。

命令

find ansible_scripts/ -follow -type f  -exec wc -c {}  \; | awk -F' ' '{n=split($0,a,"/"); print $1" "a[n]}'

输出

vagrant@ubuntu-bionic:~$ find ansible_scripts/ -follow -type f  -exec wc -c {}  \; | awk -F' ' '{n=split($0,a,"/"); print $1" "a[n]}'
59 hosts
59 main.yml
266 main.yml
30 var3.yaml
4 var2.yaml
37 var1.yaml

外壳检查状态 在线 Shell 检查状态

于 2019-09-28T16:39:35.667 回答
1

真正的挑战(shellcheck 突出显示)是处理带有嵌入空格的文件名。由于(旧版本) ls 使用换行符来分隔不同文件的输出,因此很难处理带有嵌入(或尾随)换行符的文件。

从问题和示例输出中,不清楚如何处理带有换行符的文件。

假设不需要处理带有嵌入换行符的文件名,您可以使用“wc”(使用 -c)。

(cd "$pathToDir" && wc -c *)

值得注意的是(较新版本的) ls 提供了多个选项来处理带有嵌入换行符的文件名(例如 -b)。不幸的是,即使代码正确处理了这种情况,shellcheck 也无法识别并产生相同的错误消息('use find instead ...')。

要获得对带有嵌入换行符的文件的支持,可以利用 ls 引用:

#! /bin/bash
     # Function will 'hide' the error message.
function myls {
        cd "$1" || return
        ls --b l "$@"
}

     # Short awk script to combine $9, $10, $11, ... into file name
     # Correctly handle file name contain spaces
(myls "$pathToDir") |
    awk '{ N=$9 ; for (i=10 ; i<=NF ; i++) N=N + " " $i ; print $5, N }'
于 2019-09-28T17:21:19.407 回答