D
D
Damian Lewis2021-12-12 20:35:30
linux
Damian Lewis, 2021-12-12 20:35:30

How to delete all files from a folder except for the selected ones through cmd and terminal?

There is only one question in the title, but I would be glad if you can answer several variations of this question at once.

  1. How to delete all files from a folder in Windows using cmd, except for the selected ones?
  2. How to delete all files from a folder that are less than 5 MB in size using cmd in Windows?
  3. Also interested in how to do what is described in the 1st and 2nd question on Linux systems

Answer the question

In order to leave comments, you need to log in

4 answer(s)
R
rPman, 2021-12-12
@DamianLewis

linux bash has a tool for specifying files for the parameters of any utilities it runs.
for example, if you write myapp *.txtthen a list of txt files will fly to the myapp command line.
Specifically for a task, to delete all files except those specified, you can use the following entry:
rm -f !(file.txt|data.dat)
To delete files that are larger than a certain one, you can use find (it is generally recommended to use it for many tasks, for example, you can exclude directories from the search using the -not directive) :
find . -type f -size +5M -exec rm -f {} +
upd. for windows cmd everything is sadder, you still need to search for so much mockingly inconvenient language, regular utilities that would allow you to search for files and run code on a given command as far as I know, you can write a for loop and already in its body do checks if the name is not equal to this either the size is no more ... you can not mark as an answer, I'm just too lazy and even check
the if, for / commands that are already needed somewhere? and set /? there will be exhaustive examples

O
Oleg Volkov, 2021-12-12
@voleg4u

man find

A
Alexey Kharchenko, 2021-12-12
@AVX

В общем случае - написать скрипт. Для cmd всё несколько замороченнее, и намного меньше возможностей и много ограничений. Но можно из него вызвать powershell и передать ему скрипт-блок с нужными командами.
В линуксе аналогично - выполняется на bash, но можно ведь вызвать ещё массу разных инструментов, которых уйма под линукс.
Если нужен однострочник - вторую точно можно сделать однострочником и в винде и в линуксе (гуглить за Вас не стану, это просто). В первой задаче много нюансов - файлы или папки, вложенные они или нет, и сколько их задано - одно дело когда десяток, другое когда сотни тысяч исключений. И подходы к решению будут немного разные.
А вообще, это похоже не на вопрос ("меньше/больше 5мб" - определитесь уже), а на задание в какой-то лабе. Тогда это не сюда.

Z
Zzzz9, 2021-12-13
@Zzzz9

Чем и как выбраны?

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

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question