我在使用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
(对于文件列表!)只获取大小,但结果是空格!因为数字之前的空间!当我使用分隔符时#34; "并且-f它没有工作它只给出从左侧开始的最大数字,我希望你理解我的问题
答案 0 :(得分:2)
你可以ls -l . | awk '{print $1}'
,但是你应该遵循一般的建议建议,以避免解析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 $1}'
fi
done
不使用awk获取大小(@tripleee建议):
for file in *; do
if [ -e "$file" ]; then
wc -c < "$file"
fi
done
答案 1 :(得分:2)
问题是cut
不支持将模式作为分隔符,例如[ \t]+
。这可以通过tr -s
在某种程度上得到缓解,例如如果所有行都以至少一个空格开头,则可以:
tr -s ' ' | cut -d' ' -f2
另一种方法是使用sed
从行首删除所有空格,例如:
sed 's/^ *//' | cut -d' ' -f1
另一方面,要检索文件大小,最好使用stat
:
stat -c '%s %n' *
答案 2 :(得分:1)
问题cut
它无法在分隔符中使用正则表达式
因此,将其设置为空格并询问第一个字段,仅获得
ls -l . | cut -f 1 -d " "
6928808
但是这个awk
我们将行设置为第一个字段$0=$1
,然后打印行1
:
ls -l . | awk '{$0=$1}1'
4096
0
6928808
87
281
168
345
278
6
472
375
359
358
230
230
或者你可以这样做:ls -l . | awk '{print $1}'