Linux remove file mask

Removing files with a certain extension except one file from terminal

I need to remove all files with .gif extension except one file with name say «filename.gif». What is the optimal way to go about doing this in terminal? The command rm *.gif removes all gif files including the file filename.gif .

4 Answers 4

Here’s the simple solution you should probably use:

mv filename.gif filename.gif.keep rm *.gif mv filename.gif.keep filename.gif 

There’s nothing special about the .keep extension, this just makes it so that the filename temporarily doesn’t end in .gif .

If you must not rename the file (and there are scripting situations where this is important):

for X in *.gif; do if [ "$X" != "filename.gif" ]; then rm "$X" fi done 

Or you can write it shorter like this:

for X in *.gif; do [ "$X" != "filename.gif" ] && rm "$X"; done 

You may prefer to use find instead; it’s very powerful, you might consider it more readable, and it better handles weird filenames with characters like * in them.

find . -maxdepth 1 -not -name 'filename.gif' -name '*.gif' -delete 

I’ve used the -not operator for readability, but if POSIX compliance is important—if you’re not using GNU find, or if this is for a script you intend to redistribute to others or run on a variety of systems—you should use the ! operator instead:

find . -maxdepth 1 ! -name 'filename.gif' -name '*.gif' -delete 

One handy thing about find is that you can easily modify the command for case-insensitivity, so that it finds and deletes files with extensions like .GIF too:

find . -maxdepth 1 -not -name 'filename.gif' -iname '*.gif' -delete 

Please note that I’ve used -iname in place of -name for the search pattern *.gif but I have not used it for filename.gif . Presumably you know exactly what your file is called, and -iname will match alternate capitalization not just in the extension, but anywhere in the filename.

All these solutions only delete files residing immediately in the current directory. They don’t delete files not contained in the current directory, and they don’t delete files that reside in subdirectories of the current directory.

If you want to delete files everywhere contained within the current directory (that is, including in subdirectories, and in subdirectories of those subdirectories, and so forth—files contained within the current directory or any of its descendants), use find without maxdepth -1 :

find . -not -name 'filename.gif' -name '*.gif' -delete 

You can also set other values with -maxdepth . For example, to delete files in the current directory and its children and grandchildren but not any deeper:

find . -maxdepth 3 -not -name 'filename.gif' -name '*.gif' -delete 

Just make sure you never put -delete first, before the other expressions! You’ll see I’ve always put -delete at the end. If you put it at the beginning, it would be evaluated first, and all the files under . (including files not ending in .gif and files in deep sub-sub-sub. directories of . ) would be deleted!

Читайте также:  How to delete all linux partitions

For more information, see the manual pages for bash and sh and for the commands used in these examples: mv , rm , [ , and (especially) find .

Источник

FAQ → Удаление файлов по маске в Linux

Это небольшая шпаргалка, возможно кому-то окажется полезной.
Недавно, меня озадачили вопросом, что после работы Word на файловой шаре в Samba, остаются, временные файлы, которые, по идее, должны «самоликвидироваться» после окончания работы в Word и Excel, но по непонятной причине, этого не происходит.
Собственно идея проста, как валенок, запускаем скрипт который сам обойдет все папки, т.е. рекурсивно, найдет все файлы по определенной маске и затем удалит их. Данный способ подходит для удаления различных типов файлов, по разными критериями, например можно удалять музыку или видео, которое, неразумные сотрудники закачивают в общие файловые ресурсы.
Собственно сабж.
Временные файлы MS Office имеют название ~$filename.doc (Word) и ~$filename.xslx (для Excel 2007/2010)
Предположим что файловая шара Samba находится у нас по адресу: /home/samba/public в которой уже лежат папки и файлы пользователей.
Тогда запрос принимает вид:

find /home/samba/public -type f -name "~$*.*" -delete

«~$*.*» -маска имени файла, если нужно удалить например: файлы mp3, то будет иметь вид «*.mp3», а если требуется удалять приложения, то «*.exe»
Данное задание можно засунуть в Cron и выполнять по ночам, когда сервер не используется.
Решение подходит для всех дистрибутивов Linux.

0 комментариев

FAQ

Прямой эфир

  • Artful / Seafile собственный аналог Dropbox на Ubuntu 12 июля 2019, 14:21 | 90 комментариев
  • Artful / Журнал успешных входов пользователей в систему (Windows) и запись в MySQL(Linux) 23 декабря 2018, 19:03 | 18 комментариев
  • makioro / Настраиваем VPN сервер PPTP на Mikrotik RouterOS 23 сентября 2018, 12:54 | 8 комментариев
  • kvadim / Настройка DNS+DHCP сервера для локальной сети+динамическое обновление DNS зон, под управлением Ubuntu 12.04 19 сентября 2018, 10:25 | 290 комментариев
  • Artful / Настройка MikroTik RouterBoard RB951G-2HnD (MikroTik+L2TP Beeline) 17 июля 2018, 14:27 | 77 комментариев
  • korser / Настройка OpenVPN клиента на Windows 10 7 июля 2018, 12:40 | 18 комментариев
  • Artful / Настройка шлюза локальной сети, на базе Ubuntu 12.04 10 мая 2018, 21:03 | 177 комментариев
  • Artful / Настройка PXE Boot меню с мемтестом и паролями 10 мая 2018, 21:00 | 54 комментария
  • Artful / Изменение размера раздела Software RAID в Linux (mdadm resize) 19 апреля 2018, 20:15 | 5 комментариев
  • viking-warrior / Настраиваем VPN сервер L2TP и IPsec на Mikrotik RouterOS 21 марта 2018, 06:43 | 33 комментария
  • Artful / Настройка IPTV на MikroTik ( IPTV + MikroTik + Beeline ) 5 февраля 2018, 09:00 | 11 комментариев
  • Artful / Балансировка сетевой нагрузки с помощью Nginx под Ubuntu 5 февраля 2018, 08:54 | 14 комментариев
  • Artful / Настраиваем OpenVPN клиент Linux на примере Ubuntu 5 января 2018, 09:55 | 9 комментариев
  • Jar / Сборка deb пакета Nginx из исходных кодов с добавлением сторонних модулей 31 декабря 2017, 12:21 | 1 комментарий
  • pinuskabesr / Настройка DNS-сервера BIND Master & Slave, с автоматической репликацией данных между серверами 21 декабря 2017, 20:47 | 10 комментариев
Читайте также:  Linux vnc server no password

Источник

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:

rm: cannot remove `**/*.orig': No such file or directory 

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.

@FrankBarcenas Yeah — find does everything recursively. If you want to limit how that works, you can play with the -maxdepth or -mindepth arguments.

Definitely leave the -delete at the end of the flags. find . -delete -name ‘*.orig’ will ignore the filter and clobber your whole directory.

@kamal I’d probably still use find but with its -regex or -iregex predicates. Parsing filenames (when you’re piping them around) can be hard to do safely sometimes.

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

find ./ -name ".orig" -exec rm -rf <> \; 

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

The below is what I would normally do

find ./ -name "*.orig" | xargs rm -r 

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

find ./ -name "*.orig" | grep -v "somefiletokeep.orig" | xargs rm -r 

Источник

Is there any way to delete files by a mask (*) on a remote system via SSH?

This command should delete all folders by mask cache-* on a remote server2. After execution, files aren’t deleted. If to execute this command locally on server2, files are deleted:

No. This command works fine, for example: ssh -A -o StrictHostKeyChecking=no user1@server1 ‘ssh -o StrictHostKeyChecking=no user2@server2 sudo rm -rf /folder/cache-123’

3 Answers 3

The problem here is, that * is expanded on server1 .
This should work:

ssh -A -o StrictHostKeyChecking=no user1@server1 "ssh -o StrictHostKeyChecking=no user2@server2 sudo bash -c 'rm -rf /folder/cache-*'" 

Additionally, make sure that you do not need a password for sudo on server2 .

EDIT 1:
If you have problems with globbing, use `shopt -s extglob:

ssh -A -o StrictHostKeyChecking=no user1@server1 "ssh -o StrictHostKeyChecking=no user2@server2 sudo bash -c 'shopt -s extglob; rm -rf /folder/cache-*'" 

I think it’s the right way to solve the problem, but I face an error: rm: missing operand Try ‘rm —help’ for more information.

This sounds doable. You should be able to do this with the appropriate number of backslashes. You may also benefit by running a shell.

Читайте также:  How to change linux user permissions

Recommended: to make things safer, don’t run «rm». Instead, run «echo rm». That way, you can see what each command sees.

You’re basically asking ssh to run ssh in order to run sudo in order to run rm. A problem is that neither ssh, nor the other ssh, nor sudo, nor rm are likely to support expanding * into filenames. That is done by a shell, and the shell on your local system is likely to want to expand based on local filenames. So, run a shell on the remote system.

I’ven’t the time to fully simulate this test at the moment, but something like:

ssh -A -o StrictHostKeyChecking=no user1@server1 ‘ssh -o StrictHostKeyChecking=no user2@server2 «sudo sh -c «echo rm -rf /folder/cache-*»»‘

(That ended with an asterisk, and then a backslash, and then an escaped quotation mark, and then a quotation mark, and then an apostrophe.)

Note #1: though, that sometimes I’ve had to use as many as eight backslashes to convert to a single one. (I think that may have been when remotely using something involving Regex. For a double-remote session, you might even need twice as many.) I suggest trying up to 17. (An odd backslash, like the 17th, will likely show up as a visible character. So if there are two backslashes, that may suggest 16 were treated as one, and then one left over. If there are 3, that may suggest that 8 were treated as one, and then one left over.)

ssh -A -o StrictHostKeyChecking=no user1@server1 ‘ssh -o StrictHostKeyChecking=no user2@server2 «sudo sh -c \\\\\\\\\\\\\\\\\»echo rm -rf /folder/cache-*\\\\\\\\\\\\\\\\\»»‘

Yes, blasting out way too many backslashes seems sloppier than carefully considering the reason for each need to double a backslash. But I find that for one-time tasks like building a command, this often works. Just throwing on the backslashes, and then reducing their number by one until a test ends up looking just right, is often faster than trying to analyze the situation enough to get it all perfect without guesswork.

Note #2: I’m hoping you’re using an ssh command line that lets you see the output. I do notice the Linux tag. But if your remote systems are Linux, and your local system is Windows using PuTTY which defaults to auto-closing, then you won’t see the results of your echo command. In that case, you’d either need to redirect output (which might itself be a bit of a pain regarding escaping characters on the right system), or flip a checkbox in PuTTY related to PuTTY’s «auto-close on clean exit».

Note #3: Notice the changes I made other than adding backslashes. First, I inserted » sh -c » into the mix. Also, as a reminder to a prior note I brought up, realize I changed that to » echo rm «. Of course, once things look lovely, feel free to remove the characters » echo «

Источник

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