Linux delete file by mask

Linux delete file by mask

подскажите как с помощью rm удалить все файлы с расширением *.txt ?
заранее спасибо.

Ответить | Правка | Cообщить модератору

Оглавление

  • Удалить файлы по маске *.txt, chainik, 11:49 , 13-Мрт-09, (1)
  • Удалить файлы по маске *.txt, djaarf, 14:28 , 13-Мрт-09, (2)
  • Удалить файлы по маске *.txt, Veon, 16:52 , 13-Мрт-09, (3)
    • Удалить файлы по маске *.txt, djaarf, 21:19 , 13-Мрт-09, (5)

Сообщения по теме [Сортировка по времени | RSS]

>доброго дня,
>
>подскажите как с помощью rm удалить все файлы с расширением *.txt ?
>
>заранее спасибо.

Откуда удалить? Со всех хостов инета?

1. «Удалить файлы по маске *.txt» + / –
Сообщение от chainik (??) on 13-Мрт-09, 11:49
Ответить | Правка | ^ к родителю #0 | Наверх | Cообщить модератору

2. «Удалить файлы по маске *.txt» + / –
Сообщение от djaarf (??) on 13-Мрт-09, 14:28

>доброго дня,
>
>подскажите как с помощью rm удалить все файлы с расширением *.txt ?
>
>заранее спасибо.

Чудесная утилита find тебе поможет.

Ответить | Правка | ^ к родителю #0 | Наверх | Cообщить модератору

3. «Удалить файлы по маске *.txt» + / –
Сообщение от Veon (??) on 13-Мрт-09, 16:52

>доброго дня,
>
>подскажите как с помощью rm удалить все файлы с расширением *.txt ?
>
>заранее спасибо.

find /home/vasya -name «*.txt» | xargs rm

rm *.txt, rm -r *.txt

В зависимости от контретной ситуации

Ответить | Правка | ^ к родителю #0 | Наверх | Cообщить модератору

5. «Удалить файлы по маске *.txt» + / –
Сообщение от djaarf (??) on 13-Мрт-09, 21:19

>>доброго дня,
>>
>>подскажите как с помощью rm удалить все файлы с расширением *.txt ?
>>
>>заранее спасибо.
>
>find /home/vasya -name «*.txt» | xargs rm

Можно обойтись одним find
find path -type f -name «*.txt» -delete
>
>rm *.txt, rm -r *.txt
>
>В зависимости от контретной ситуации

Источник

Команды для удаления большого количества файлов в Linux

Удаление старых файлов linux по маске чаще всего осуществляется следующим образом:

Веб-сервер указан для примера. Синтаксис очень прост — команда принудительно удалит все файлы с расширением .log в указанном каталоге, при этом удаление будет рекурсивным(-r — recursive) и подтверждения система при этом спрашивать не будет (-f — force).

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

Если rm -rf не помогает — удалять файлы следует в цикле for. Для каждого файла будет отдельная операция удаления и никаких ограничений системы здесь ожидать не приходится.

Синтаксис в простейшем случае может выглядеть так:

for f in /var/log/apache2/*.log; do rm «$f»; done

В цикл for можно добавить любую дополнительную логику.

Удаление старых файлов в Linux по Cron

Логи или другие файлы (сессии РНР) можно удалять как используя циклы (так приходится делать обычно если логов или других файлов накопилось действительно очень много), но если система не запущена или только создается лучше использовать регулярно выполняемое задание Cron, согласно которому с заданной периодичностью будут удаляться файлы определенных типов

# m h dom mon dow command

23 3 * * * find /var/www/web/sites/server-gu.ru/www/var/session/ -type f -mtime 7 -exec rm -f <> \;

В примере удаляются сессии РНР для сайта старше 7 дней.

В цикле то же самое можно сделать так:

for f in /tmp/logs/*.log

find $f -mtime +7 -exec rm <> \;

Приведенное выражение, как и любой другой цикл можно поместить в файл, сделать его исполняемым и с тем же успехом выполнять по Cron

Источник

Recursively delete all files with a given extension [duplicate]

I want to delete all *.o files in a directory and its sub-directories. However, I get an error:

On the other hand, rm *.o works, but it’s not recursive.

2 Answers 2

That is evil: rm -r is not for deleting files but for deleting directories. Luckily there are probably no directories matching *.o .

What you want is possible with zsh but not with sh or bash (new versions of bash can do this, but only if you enable the shell option globstar with shopt -s globstar ). The globbing pattern is **/*.o but that would not be limited to files, too (maybe zsh has tricks for the exclusion of non-files, too).

But this is rather for find :

or (as I am not sure whether -delete is POSIX)

That’s not quite how the -r switch of rm works:

rm has no file searching functionality, its -r switch does not make it descend into local directories and identify files matching the pattern you give it. Instead, the pattern ( *.o ) is expanded by the shell and rm will descend into and remove any directories whose name matches that pattern. If you had a directory whose name ended in .o , then the command you tried would have deleted it, but it won’t find .o files in subdirectories.

What you need to do is either use find :

or, for non-GNU find :

Alternatively, if you are using bash you can enable globstar :

NOTE: all three options will delete directories whose name ends in .o as well, if that’s not what you want, use one of these:

Источник

How do I remove all files that match a pattern?

When I revert in Mercurial, it leaves several .orig files. I would like to be able to run a command to remove all of them.

I have found some sources that say to run:

But that gives me the message:

I have also tried these commands:

4 Answers 4

Use the find command (with care!)

I’ve commented out the delete command but once you’re happy with what it’s matching, just remove the # from the line and it should delete all those files.

«find» has some very advanced techniques to search through all or current directories and rm files.

I have removed all files that starts with .nfs000000000 like this

The below is what I would normally do

It’s a good idea to check what files you’ll be deleting first by checking the xargs . The below will print out the files you’ve found.

If you notice a file that’s been found that you don’t want to delete either tweak your initial find or add a grep -v step, which will omit a match, ie

Not the answer you’re looking for? Browse other questions tagged uninstall delete or ask your own question.

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.10.8.40416

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

How can I delete all files with a particular extension in a particular folder?

If I set the current/working directory (navigating to it using cd ) to some particular directory and then type:

What will this command do? Is it true that the above command will only delete files with the extension .xvg only in the working directory?

I was nervous about trying this before asking, because I want to be absolutely sure that the above command will only delete .xvg files LOCATED IN THE WORKING DIRECTORY.

4 Answers 4

Yes, rm *.xvg will only delete the files with the specified extension in your current directory.

A good way to make sure you are indeed in the directory you want delete your files is to use the pwd command which will display your current directory and then do an ls to verify you find the files you are expecting.

If you are bit apprehensive about issuing the rm command, there are 2 things you can do:

type ls *.xvg to see a list of what files would be affected by this command.

Unless you have a lot of files, you could always also use the -i command line switch for rm (also exists for cp and mv ). Using rm -i *.xvg would prompt you for each individual file if it was ok to delete it, so you could be sure nothing you didn’t expect was getting deleted. (This will be tedious if you have a lot of files though 🙂

You don’t need to navigate to the dir, just use

In the case you have a typo or similar mistake in the path, where /som/dir does not exist:

will accidentally delete all .xvg-files in the current dir. The first command will not, and you don’t need to cd back again.

An alternative way would be to use find:

Yes, rm *.xvg will only delete files ending with .xvg in your current directory. Here’s why.

When you type a command like this, work is split up between the shell you are using (let’s assume bash) and the command binary.

You can locate the binary by typing which rm . This little program takes care of unlinking files. Programs like this can be started from the command line and can read a list of arguments prog arg1 arg2 arg3 when they start up. In the case of rm , they are interpreted as a list of fully qualified filenames to be deleted. So if you are in a directory containing the file foo.bar , typing delete ‘foo.*’ will result in rm: foo.*: No such file or directory . Note the single quotes around the file pattern, they tell the shell to pass the argument to the shell as it is.

However if you type rm *.bar in the same directory, it will delete the file. What’s happening here is that your shell, which is the program you are using to type in commands, is performing some transformations before passing the arguments on to the command. One of these is called ‘file name expansion’, otherwise know as ‘globbing’. You can see a list of bash file name expansions here. One of the most common expansions is * , which is expanded to filenames in the current directory.

A simple way to look at globs at work is to use echo , which prints back all arguments passed to it through the shell. So typing echo * in the same directory will output foo.bar . So when you type rm *.bar , what’s actually happening is that the shell expands the argument list to foo.bar , then passes that to the rm command.

There are some ways of controlling globbing. In recent versions of bash, for example, you can turn on an option called globstar which will do recursive expansion. Typing echo **/*.bar will show a list of all files ending in .bar in all subfolders. So typing rm **/*.bar in globstar enabled bash will indeed recursively delete all matching files in subfolders.

Источник

Читайте также:  Сетевой драйвер для windows 10 64 bit для ноутбука acer
Оцените статью