1

I have 10 files in Unix folder with .txt extension. Here I need to get all files apart from fgh.txt (any one) file. What is the UNIX Command?

1.abc.txt
2.bcd.txt
3.cde.txt
4.def.txt
5.efg.txt
6.fgh.txt
7.ghi.txt
8.hij.txt
9.ijk.txt
10.jkl.txt

Here I need to get all files apart from the file 6.fgh.txt. What is the UNIX Command?

  • 1
    What do you mean by "get"? – Kusalananda Aug 30 '17 at 9:57
  • Could you correlate the leading text ("apart from fgh.txt") with the trailing text ("apart from the file 6.fgh.txt")? Do you have a partial filename match in mind, or a specific file? – Jeff Schaller Aug 30 '17 at 11:41
  • If any of the answers solved your problem, please indicate so with the checkmark next to it. Thank you! – Jeff Schaller Sep 10 '17 at 12:52
3

With find command:

find . -type f -name "*.txt" ! -name "fgh.txt"
  • -name "*.txt" - to find files with names corresponding the pattern (all txt file)

  • ! -name "fgh.txt" - except the exact filename fgh.txt


If your files are really prefixed with numbers (I'm not sure about that question's edit) change the negation condition to ! -name "*fgh.txt"

  • It's probably worth pointing out that this will recurse into subdirectories by default, so it may return more than is needed. – Austin Hemmelgarn Aug 30 '17 at 12:40
3

The extglob option of the bash does the trick:

Extended globbing as described by the bash man page:

?(pattern-list) Matches zero or one occurrence of the given patterns
*(pattern-list) Matches zero or more occurrences of the given patterns
+(pattern-list) Matches one or more occurrences of the given patterns
@(pattern-list) Matches one of the given patterns
!(pattern-list) Matches anything except one of the given patterns

The commands you need (to exclude any *fgh.txt file):

shopt -s extglob
ls -d -- !(*fgh).txt

If you want to exclude a specific file based on its full filename:

ls -d -- !(6.fgh.txt)
  • !(6.fgh.txt) would include non-txt files. !(6.fgh).txt for all txt files except 6.fgh.txt. – Stéphane Chazelas Aug 30 '17 at 11:42
2

Simple and elegant (assuming GNU ls):

ls -I fgh.txt
1

If you want that list of files in an array, in zsh, you have a few options:

setopt extendedglob # best in ~/.zshrc

# using the negation glob operator:
files=((^*fgh).txt)

# using the "except" glob operator:
files=(*.txt~*fgh*)

# trimming entries from the array afterwards:
files=(*.txt)
files=(${files:#*fgh*})

Then use your array as you please like:

ls -ld -- $files

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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