shell to remove the first ie. earlier file/folder of list pattern with pairs of almost identical

How do Bash shell remove the first ie. earlier file/folder of list pattern with pairs of almost identical name such illustration;
(the real is not directly from ls but it's result from pipe)

1
2
3
4
5
6
7
8
9
10
$ ls

aaa
aab
bbb
bbc
mmm
mmn
xxx
xxy



just illustration: ls | rm ...? to finally get

1
2
3
4
5
6
$ ls

aab
bbc
mmn
xxy


How ?
Last edited on
Eg.

List all files beginning with a or b
 
ls [ab]*


Apply some command to that list.
 
ls [ab]* | xargs -d'\n' rm


Another way
 
rm $(ls [ab]*)
note that parsing ls (by feeding it to xargs, or using a command substitution) is dangerous and easy to break: http://mywiki.wooledge.org/ParsingLs Command substitutions should almost always be quoted: http://mywiki.wooledge.org/Quotes. There's also no reason to use ls in this case. Just pass the glob directly to rm:

1
2
3
4
5
6
7
8
9
~/tmp λ touch aaa aab bba bbb bbc
~/tmp λ echo [ab]*
aaa aab bba bbb bbc
~/tmp λ rm -v [ab]*
aaa
aab
bba
bbb
bbc


edit: https://shellcheck.net is also a great resource if you're going to be writing shellscripts
Last edited on
Remove the first 17 files listed (with the above caveats on using xargs):
ls | head -17 | xargs rm

Remove the 17 newest files:
ls -t | head -17 | xargs rm

Remove the oldest 12 files:
ls -tR | head -13 | xargs rm

etc.
If the task would be just to get the words, which have a triple of the first character:
1
2
3
for X in aaa wyyy xyxxx aba aax bbc bbb
do echo ${X} | grep -E "${X:0:1}{3,3}"
done

aaa
xyxxx
bbb



Bash has also extended globbing. See https://www.linuxjournal.com/content/bash-extended-globbing
Last edited on

Remove the first 17 files listed (with the above caveats on using xargs):

and the above (terribly dangerous and insecure) caveats of using ls in a pipeline. Seriously, it's better to just not use it, and there's almost no reason.


for X in aaa wyyy xyxxx aba aax bbc bbb
do echo ${X} | grep -E "${X:0:1}{3,3}"
done


X should be quoted. ${X} is exactly the same as $X here, and the {} portion does nothing to prevent wordsplitting http://mywiki.wooledge.org/Quotes.

The linux Journal link also has quite a few incorrect statements as well. Saying that those characters may have been chosen because of their RE equivalents may be correct, but then keeps referring to the glob as an RE, which isn't correct. They're a different syntax as an RE. http://mywiki.wooledge.org/glob#extglob and https://wiki.bash-hackers.org/syntax/pattern?s[]=extglob#extended_pattern_language are both great resources for extglobs
Last edited on
Like for example creating a file called '-rf', then try and remove it without blowing away an entire tree.

Last edited on
Like for example creating a file called '-rf', then try and remove it without blowing away an entire tree.
rm -- -rf
Registered users can post here. Sign in or register to post.