剪切文本文件并获取第一个字段 bash

cut text file and get the first field bash

我在使用 grep 或 cut 命令获取文件大小时遇到​​了问题 我有那个文件:

   4096 Feb 15 21:52 f1
      0 Feb 15 18:24 f4
6928808 Feb 10 16:59 install_flash_player_11_linux.i386.tar.gz
     87 Feb 14 18:43 sc1.sh
    281 Feb 14 19:11 sc2.sh
    168 Feb 14 21:40 sc3.sh
    345 Feb 15 21:15 sc4.sh
    278 Feb 15 19:27 sc4.sh~
      6 Feb 15 18:27 sc5.sh
    472 Feb 16 11:01 sc6.sh
    375 Feb 16 11:01 sc6.sh~
    359 Feb 17 01:18 sc7.sh
    358 Feb 17 01:17 sc7.sh~
    230 Feb 16 09:31 toUppefi.sh
    230 Feb 16 02:07 toUppefi.sh~

例如,我每次只需要下车第一个号码:

4096
0
...

我使用 ls -l . | cut -d" " -f5(用于文件列表!)只获取大小,但结果是 spaces!因为数字前的 space !当我使用定界符“”和 -f 它不起作用时它只给出从左侧开始的最大数字,我希望你理解我的问题

您可以 ls -l . | awk '{print }',但您应该遵循一般建议以避免解析 ls 的输出。

避免解析 ls 输出的常用方法是遍历文件以获取所需信息。要获取文件的大小,您可以使用 wc -c.

for file in *; do
    if [ -e "$file" ]; then   #test if file exists to avoid problems with an empty directory
        wc -c "$file"
    fi
done

如果您真的只需要大小 - 只需通过 awk 管道即可。

for file in *; do
    if [ -e "$file" ]; then
        wc -c "$file" | awk '{print }'
    fi
done

不使用 awk 获取大小(@tripleee 建议):

for file in *; do
    if [ -e "$file" ]; then
        wc -c < "$file"
    fi
done

问题 cut 它不能在定界符中使用正则表达式。
所以将它设置为 space 并要求第一个字段你只得到

ls -l . | cut -f 1 -d " "
6928808

但是这个 awk 我们将行设置为第一个字段 [=14=]= 然后打印行 1:

ls -l . | awk '{[=11=]=}1'
4096
0
6928808
87
281
168
345
278
6
472
375
359
358
230
230

或者您可以这样做:ls -l . | awk '{print }'

问题是 cut 不支持模式作为分隔符,例如[ \t]+。这可以通过 tr -s 在某种程度上缓解,例如如果所有行都以至少一个 space 开头,这有效:

tr -s ' ' | cut -d' ' -f2 

另一种方法是使用 sed 从行首删除所有白色 space,例如:

sed 's/^ *//' | cut -d' ' -f1

另一方面,要检索文件大小,您最好使用 stat:

stat -c '%s %n' *