Linux show files with size

Linux ls to show only filename date and size

How can I use ls in linux to get a listing of filenames date and size only. I don’t need to see the other info such as owner or permission. Is this possible?

ls is great because it has very fast sorting by datetime, but the formatting is hard to deal with. I suggest using a token at —time-style like —time-style=’+&%Y%m%d+%H%M%S.%N’ where the token is ‘&’, using that as reference you can further parse the output with sed so you can also backtrack as just before the token is the size! If someone want to post that as a complete answer, feel free to, I am too asleep right now 🙂

9 Answers 9

To output in columnar format:

This is nice, but it does have the «environment too large» /»argument list too long» problem potentially.

🙂 Just a proof of concept. In Real Life[tm] this will be a find . -type f -print0 | xargs -0 stat -c «%y %s %n»

To format the output of stat , you can add width information to the format string like C printf function, e.g. «%y %8s %n» , it’s not documented, but seems works (coreutils 8.17, Fedora 18)

You could always use another utility like awk to format the output of ls 1 :

1.Yes, generally, you shouldn’t parse the output of ls but in this case the question specifically calls for it.

That doesn’t print the file size though. And it only prints the first part of filenames with whitespace in them. And it can fail if ls is aliased (say alias ls=’ls -i’ ). You really should take a lot of care if you want to go about parsing ls output.

I had the file size in there and then edited it out (vague moment) — I’ll restore it. And I agree about all the caveats re parsing ls , but that is what the OP wanted.

I disagree, the OP wants the filenames, not the first part of filenames if the filename happens to have whitespace. (Using /bin/ls would avoid the alias problem.)

That is understood implicitly: what is stated explicitly is that OP wants a solution with ls which we both agree is not going to satisfy the whitespace requirement. The /bin/ls suggestion is a good one.

Читайте также:  Развернуть виртуальную машину linux

love this solution; in regards to previous comments about not printing size, you can get size with ls, and can use -h to make it human-readable. Specifically I used: ls -lah | awk ‘‘ which yields: 4.0K Jan 24 18:17 . Granted, the original solution doesn’t say anything about awk, but in linux we should assume the output of a process will always be the input to another process, right? 😉

You can get a lot of control about how you list files with the find utility. ls doesn’t really let you specify the columns you want.

$ find . -maxdepth 1 -printf '%CY%Cm%Cd.%CH%CM\t%s\t%f\n' 20111007.0601 4096 . 20111007.0601 2 b 20111001.1322 4096 a 

The argument to the printf action is a detailed in the manpage. You can choose different time information, what size you want (file size or disk blocks used), etc. You can also make this safe for unusual file names if further processing is needed.

Источник

How do I get the find command to print out the file size with the file name?

This version will exec «ls» process for each file. If you have many files (say, over a thousand) you better optimize that by either: find . -name ‘*.ear’ -exec ls -lh <> + \; (GNU extension) or find . -name ‘*.ear’ -print0 | xargs -0 ls -lh . Also you may like to add -type f if you’re only interested in files (or add -d to ls if you want directories themselves included without their contents).

Your answer does not exclude directories, so you will end up running ls on directories as well, which clearly is not the right thing to do.

This is a really inefficient way of doing things — and unfortunately ash108’s comments are also not ideal. It’s much better to use the -printf option to find.

dmazzoni’s answer is much more efficient because it avoids a fork+exec on every file (100x faster on my machine). I had to change %k to %s. @FaheemMitha: you can add options like -type f to only count regular files.

You need to use -exec or -printf. Printf works like this:

find . -name *.ear -printf "%p %k KB\n" 

-exec is more powerful and lets you execute arbitrary commands — so you could use a version of ‘ls’ or ‘wc’ to print out the filename along with other information. ‘man find’ will show you the available arguments to printf, which can do a lot more than just filesize.

Читайте также:  Samsung magician for linux

[edit] -printf is not in the official POSIX standard, so check if it is supported on your version. However, most modern systems will use GNU find or a similarly extended version, so there is a good chance it will be implemented.

It looks like your example is more precise, but I can’t seem to get the example to work on Solaris 10.

I’m afraid Solaris find does not support -printf at all: jrwren.wrenfam.com/blog/2006/10/07/solaris-find-sucks cs.bgu.ac.il/~arik/usail/man/solaris/find.1.html You could install GNU find if you can be bothered, otherwise you need to use exec or | as suggested by others.

+1 This seems more cleaner. To format the output I would prefer add column command. find . -name *.ear -printf «%p %k KB\n» | column -t

A simple solution is to use the -ls option in find:

That gives you each entry in the normal «ls -l» format. Or, to get the specific output you seem to be looking for, this:

find . -name \*.ear -printf "%p\t%k KB\n" 

Which will give you the filename followed by the size in KB.

Using GNU find, I think this is what you want. It finds all real files and not directories (-type f), and for each one prints the filename (%p), a tab (\t), the size in kilobytes (%k), the suffix » KB», and then a newline (\n).

find . -type f -printf '%p\t%k KB\n' 

If the printf command doesn’t format things the way you want, you can use exec, followed by the command you want to execute on each file. Use <> for the filename, and terminate the command with a semicolon (;). On most shells, all three of those characters should be escaped with a backslash.

Here’s a simple solution that finds and prints them out using «ls -lh», which will show you the size in human-readable form (k for kilobytes and M for megabytes):

As yet another alternative, «wc -c» will print the number of characters (bytes) in the file:

Источник

Размер файла в Linux

В этой небольшой статье мы поговорим о том, как узнать размер файла в Linux с помощью различных утилит. Проще всего узнать этот параметр в графическом интерфейсе, но многим часто приходится работать в терминале и надо знать как эта задача решается там.

Вы узнаете как посмотреть размер файла через файловый менеджер, утилиту ls, а также du. Об этих утилитах у нас есть отдельные статьи, но эта будет нацелена именно на просмотр размера конкретного файла.

Читайте также:  Error 1962 no operating system found linux

Размер файла в Linux

1. Nautilus

Чтобы посмотреть размер файла в файловом менеджере сначала найдите нужный файл и кликните по нему правой кнопкой мыши. В открывшемся меню выберите Свойства:

Программа откроет окно, в котором будут указаны свойства файла, среди них будет и размер:

2. Команда ls

Для того чтобы утилита ls отображала размер файлов в удобном для чтения формате необходимо использовать параметр -h. Например:

Здесь размер отображается в пятой колонке. Чтобы увидеть размер определённого файла надо передать его имя утилите:

ls -lh ‘Снимок экрана от 2020-08-10 20-22-50.png’

Можно ещё вручную указать единицы измерения для показа размера. Для этого используйте опцию —block-size. Например, мегабайты:

Вместо ls можно использовать команду ll, её вывод полностью аналогичен команде ls -l:

3. Утилита stat

Программа stat кроме метаданных позволяет выводить размер файла в байтах. Например:

stat ‘Снимок экрана от 2020-08-10 20-22-50.png’

Если нужно показать только размер, используйте опцию с указанием формата %s:

stat -c %s ‘Снимок экрана от 2020-08-10 20-22-50.png’

4. Утилита du

Программа du специально предназначена для просмотра размера файлов в папке. Вы можете просмотреть размер конкретного файла, например:

du -h ‘Снимок экрана от 2020-08-10 20-22-50.png’

Опция -h включает вывод размера в удобном для чтения формате. Если вы хотите посмотреть размеры для всех файлов в папке, просто передайте путь к папке:

А чтобы узнать размер папки в Linux используйте опцию -s. Она суммирует размеры всех объектов:

5. Утилита ncdu

Программа ncdu позволяет анализировать дисковое пространство занимаемое файлами и каталогами. Но она не поставляется вместе с системой. Для её установки выполните:

Затем просто укажите в параметрах каталог, размер которого вы хотите посмотреть:

Все файлы будут отсортированы по размеру, а в самом низу будет отображен общий размер этой папки:

6. Утилита find

С помощью этой утилиты вы не можете узнать размер файла, зато можете найти файлы с определённым размером. С помощью параметра size можно указать границы размера файлов, которые надо найти. Например, больше чем 2000 килобайт, но меньше чем 2500 килобайт:

find ~/Изображения/ -size +2000k -size -2500k

Размер можно ещё указывать в мегабайтах для этого используйте приставку M, или в байтах, тогда никакой приставки не нужно.

Выводы

В этой небольшой статье мы разобрались как узнать размер файлов linux, а также как посмотреть размер каталога и всех файлов в нём с помощью различных утилит. А какие способы просмотра размера используете вы? Напишите в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

Оцените статью
Adblock
detector