0

I want to find a hidden file with a name that is 2 or 3 characters long on a Linux machine.

I tried:

ls .?[a-zA-Z][a-zA-Z]
ls .??[a-zA-Z] 

I also tried find . -name "???" and find . -name "??" but it only shows filenames with 3 and 2 characters respectively.

1

A filename that is hidden always starts with a dot. A hidden filename that is two characters long, including the initial dot, would be matched by .?, while .?? would match hidden filenames that are three characters long.

Assuming that you want names of regular files, not directories and other filetypes, then you would be able to use

find . -type f \( -name '.?' -o -name '.??' \)

This would find regular files in or below the current directory whose names are hidden and two or three characters long.

If you're using the bash shell, and are only interested in names in the current directory:

shopt -s nullglob
for name in .? .??; do [[ -f $name ]] && printf '%s\n' "$name"; done

This would loop over all the names that matches either of the two patterns (if there are any), and print out the ones that corresponds to regular files or symbolic links to regular files.

Setting the nullglob shell option in bash ensures that a pattern is removed completely if it doesn't match any names, rather than remain unexpanded.

By also setting the extglob shell option in bash, the two patterns .? and .?? could be combined into .@(?|??) (or possibly .??(?), but that's a bit obfuscated).

In the zsh shell, you can make the pattern only match regular files by means of a glob qualifier, and therefore don't need that loop:

printf '%s\n' .(?|??)(.)

Here, the (.) is the globbing qualifier that restricts the matching of names to only regular files.

3
  • Can I look for 2 or 3 characters with the help of ls and/or echo cmd?
    – Gaz96
    Nov 5 '20 at 20:30
  • @Soham Not in bash if you only want regular files. You would need a loop, as I've shown.
    – Kusalananda
    Nov 5 '20 at 20:36
  • Or printf '%s\n' .(?|??)(-.) if you want that test of file type to be done after symlink resolution like with the [[ -f $name ]] approach. Nov 5 '20 at 20:42
0

GNU find version 4.6.0 in Bash CentOS 8:

find . -type f -name '.??' -o -name '.???'

That will find hidden files with either two or three characters.

If you are counting the . as one of the characters:

find . -type f -name '.?' -o -name '.??'
2
  • Can I look for 2 or 3 characters with the help of ls and/or echo cmd?
    – Gaz96
    Nov 5 '20 at 20:26
  • @Soham No, this is not possible.
    – Alex
    Nov 5 '20 at 20:54

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.