Rm * excluding one file

 
Thread Tools Search this Thread
Top Forums UNIX for Beginners Questions & Answers Rm * excluding one file
# 8  
Old 05-08-2017
A bit out of box and assuming that you want to retain the most recently modified file, rename the file you want to keep by giving it a leading dot, then remove everything else and rename the file back:-
Code:
# Work out file to be retained
save_file="$(ls -1rt |tail -1)"
mv "$save_file" ".$save_file"

# Delete everything else
rm *

# Move my file back
mv ".$save_file" "$save_file"

Would that work for you?

Perhaps also, list the files, stripping out the most recent:-
Code:
ls -1t | sed '1 d' | xargs rm


I hope that these help.
Robin
# 9  
Old 05-08-2017
Quote:
Originally Posted by rbatte1
A bit out of box and assuming that you want to retain the most recently modified file, rename the file you want to keep by giving it a leading dot, then remove everything else and rename the file back:-
Code:
# Work out file to be retained
save_file="$(ls -1rt |tail -1)"
mv "$save_file" ".$save_file"

# Delete everything else
rm *

# Move my file back
mv ".$save_file" "$save_file"

Would that work for you?

Perhaps also, list the files, stripping out the most recent:-
Code:
ls -1t | sed '1 d' | xargs rm

I hope that these help.
Robin
Hello Robin,

IMHO I think directly giving rm * could be dangerous in case we are not running the script in the same path where user actually wants to perform the actions. So I believe it will more good if we could add path here and check the condition if path exist too(my fav. Bakunin style Smilie)
Code:
if [[ -d /my/path/for/actions_to_be_performed/ ]]
then
       cd /my/path/for/actions_to_be_performed/
       rm * ### Or whatever action needed by user
else
       echo "Path /my/path/for/actions_to_be_performed/ does not exist."
fi

Thanks,
R. Singh
# 10  
Old 05-08-2017
Given the small number of files that you want to remove:
Code:
rm -i *

would suffice. Alternatively you could remove the write-attribute of the file(s) you wish to preserve. This would cause rm to prompt for their removal whilst quietly removing all other files. Just remember to put it back afterwards.

Andrew
# 11  
Old 05-09-2017
If you have a varying list of files whose names all begin with MM_ and you want to remove all but the last name sorted alphanumerically, none of the filenames contain any IFS characters (by default <space>, <tab>, and <newline>), the list of files you're removing will never give you a command length that would exceed ARG_MAX, and you're using a shell that meets POSIX shell requirements (with or without extensions like shopt and setopt). You could also try:
Code:
last=''
list=''

for file in MM_6000*
do	list="$list $last"
	last="$file"
done
[ ${#list} -gt 0 ] && rm $list

which is similar to what Corona688 suggested, but only invokes rm once instead of once for each file to be removed. (But his suggestion works without the limitations noted above except the 1st and last.)

Note: The problem noted by MadeInGermany in post #13 in this thread has been fixed above.

Last edited by Don Cragun; 05-09-2017 at 05:38 AM.. Reason: Fix bug noted by MadeInGermany.
This User Gave Thanks to Don Cragun For This Post:
# 12  
Old 05-09-2017
So many ways to skin a cat!

Don Cragun's method using bash4 arrays:
Code:
files=(MM_6000*)
rm ${files[*]:0:${#files[*]}-1}

Same caveats as above, of course.

Andrew
# 13  
Old 05-09-2017
Don's does not discard the last file, a correction is
Code:
list="" last=""
for file in MM_6000*
do
  list="$list $last"
  last=$file
done
[ ${#list} -gt 0 ] && rm $list

Another array variant (bash only):
Code:
files=(MM_6000*)
unset files[${#files[@]}-1] # delete the last array element
echo "${files[@]}"

(Replace echo with rm)

Last edited by MadeInGermany; 05-09-2017 at 05:28 AM..
These 3 Users Gave Thanks to MadeInGermany For This Post:
# 14  
Old 05-09-2017
Quote:
Originally Posted by apmcd47
So many ways to skin a cat!

Don Cragun's method using bash4 arrays:
Code:
files=(MM_6000*)
rm ${files[*]:0:${#files[*]}-1}

Same caveats as above, of course.

Andrew
Not quite. If you run my (corrected) script twice, the 2nd execution will silently do nothing (since only one matching file remains). The code above will run rm with no file operands the 2nd time you run it (or any time that there are no files or only one file matching the pattern MM_6000*). And MadeInGermany's code has this same issue.

The above can be fixed using:
Code:
files=(MM_6000*)
[ ${#files[*]} -gt 1 ] && rm ${files[*]:0:${#files[*]}-1}

and I think MadeInGermany's suggested code can be fixed with:
Code:
files=(MM_6000*)
unset files[${#files[@]}-1] # delete the last array element
[ ${#files[@]} -gt 0 ] && echo "${files[@]}"

again, replacing echo with rm if the resulting list of files produced is what you expect.

A slightly modified version of this also works with a recent Korn shell (tested with ksh version 93u+ 2012-08-01):
Code:
files=(MM_6000*)
unset files[$((${#files[@]}-1))] # delete the last array element
[ ${#files[@]} -gt 0 ] && echo "${files[@]}"

Both of the above suggestions work even with filenames that contain whitespace characters, but are still susceptible to ARG_MAX limits.
This User Gave Thanks to Don Cragun For This Post:
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. UNIX for Dummies Questions & Answers

ConCATenating binaries but excluding last bytes from each file

Hi there, shameful Linux Newbie here :p I was wondering if you could help with my problem... I have plenty of files I'd like to concatenate. I know how to basically use cat command but that won't be enough from what I need : excluding the last xx bytes from files before assembling since there's... (4 Replies)
Discussion started by: grolido
4 Replies

2. UNIX for Dummies Questions & Answers

Finding new file, but excluding directory..

hi, I need to find files that have been created less than 3 days ago. However, I need to only search specific directories. I've searched about the net and found some useful commands such as : find . -type d -name 'dir_to_exclude' -prune -o -print -mtime -3 however I cannot get it... (2 Replies)
Discussion started by: horhif
2 Replies

3. Shell Programming and Scripting

Read file excluding XML in it

Hi , I have a file like below.I want all the content in a single line excluding the XML.How can i proceed? t=21 y=23 rg=xyz ..... <xmlstarts> . . <xmlends> lk=99 lo=09 (3 Replies)
Discussion started by: chetan.c
3 Replies

4. Shell Programming and Scripting

Excluding file from tar

Hello i am using HP-UX rapdb2 B.11.23 U ia64 1068321383 unlimited-user license. I am tryiyng to exclude for tar all files that start with TOT* but i doues not work I am using: tar -cvf /ODS/prepaid/CDR_FLOW/WORK/backup.tar --exclude='TOT*' and i get the error: tar: cannot stat... (3 Replies)
Discussion started by: chriss_58
3 Replies

5. UNIX for Advanced & Expert Users

Excluding a file from tar...

The title is not as easy as it sounds.... I am trying to exclude and file while ssh and untaring the file on the fly. The command I am using is... The command typically works but recently I've add the X option along with the exclude file. Essentially, the exclude file is being ignored when run... (2 Replies)
Discussion started by: lwif
2 Replies

6. Solaris

how to find out the file's name excluding string?

Hello, Under one directory, I can use below command to find out the file names with string "Export terminated successfully without warnings" grep -i -l "Export terminated successfully without warnings" *.* My question is : how I find out the file names without including string "Export... (5 Replies)
Discussion started by: GreatJerry
5 Replies

7. Shell Programming and Scripting

Excluding certain paras from a file

Hi, I have a log file which might have certain paragraphs. Switch not possible Error code 1234 Process number 678 Log not available Error code 567 Process number 874 ..... ...... ...... Now I create an exception file like this. cat text.exp Error code 1234 Process number 874 (3 Replies)
Discussion started by: kaushys
3 Replies

8. UNIX for Advanced & Expert Users

find excluding a directory and a file

Hi I have some 5 folders and two files in the current directory. I want to delete all, expect one folder(files in the folder too should not be deleted) and a file in the current directory. Lets say the folder and file that should not be deleted as 'a'(folder name) and 'b'(file name). Can you... (1 Reply)
Discussion started by: ammu
1 Replies

9. UNIX for Dummies Questions & Answers

Get the name of the file excluding the extension

How to get the name of the file by excluding the extention of file name? For example, my filename is 'test.txt'. I want to get only the name 'test' but not the extention .txt. (2 Replies)
Discussion started by: vinay123
2 Replies

10. UNIX for Dummies Questions & Answers

Excluding a file type from an archive

:confused: I'm trying to archive a site excluding all PDF files in order to keep the size down. I have manged to do this in the past using the exclude argument in the tar command and something along the lines of *.pdf. Unfortunately, I failed at the time to note the syntax that I used and have... (1 Reply)
Discussion started by: Stuart
1 Replies
Login or Register to Ask a Question