1

I want to use this alias for all files that end with .txt

$ f "*.txt"

I expect to get all files that end with txt like foo.txt and bar.txt, not a file called ".txt" The problem is that this command is this searching for files called ".txt" not count * as a glob.

my .bashrc:

#f
f() {
    sudo find . -name "$1" 2> /dev/null | grep --color=always $1
}

# F
F() {
    sudo find / -name "$1" 2> /dev/null | grep --color=always $1
}
Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476
smalinux
  • 1,083
  • 2
  • 12
  • 27
  • 1
    It's not clear to me what exactly you are trying to do. If, for instance, you run `f '*.txt'` and `find` outputs `./a/b/c.txt`, which part of the output do you want coloured. (Possibilities that come to mind are the whole line, `/c.txt`, `c.txt`, or `.txt`.) – pjh Feb 16 '22 at 00:20
  • @pjh Not sure if this is clean code, but this works for me anyways, https://stackoverflow.com/a/71135208/5688267 Thanks. – smalinux Feb 16 '22 at 00:58

2 Answers2

1

Shell glob syntax and regexes are two different syntaxes. You can't use them interchangeably.

Fortunately, you don't need to get grep involved.

find . -name '*.txt'

will find all the files that end in .txt. If you want to exclude .txt then change your glob pattern to require at least one character.

find . -name '?*.txt'

Side note: Putting sudo in a shell alias is a bad idea. You only want to run sudo when you specifically ask for it.

Andy Lester
  • 86,927
  • 13
  • 98
  • 148
  • I'm sorry, right, I mean shell glob. that is work find, I want to make an alias that's act like this. I'm using grep for coloring try 'find . -name '*.txt' | grep --color=always "*.txt"`, I will remove sudo, thank you – smalinux Feb 15 '22 at 21:57
-1

This works for me.

# f
f() {
    p1="sudo find . -name \"${1}\""
    p2="2> /dev/null"
    p3="grep --color=always \".${1}\""
    eval ${p1} ${p2} "|" ${p3}
}

# F
F() {
    p1="sudo find / -name \"${1}\""
    p2="2> /dev/null"
    p3="grep --color=always \".${1}\""
    eval ${p1} ${p2} "|" ${p3}
}
smalinux
  • 1,083
  • 2
  • 12
  • 27
  • 1
    See [Why should eval be avoided in Bash, and what should I use instead?](https://stackoverflow.com/q/17529220/4154375). Using `eval` on unsanitized input data (like `$1`) is a bad idea. Using it with `sudo` is a **really** bad idea. Try `f '$(echo rm -rf /* >&2)'` (but make absolutely sure not to omit the `echo`!). – pjh Feb 16 '22 at 01:52
  • 1
    Try running `f '*"*'` to find all files with double quote characters in their names. – pjh Feb 16 '22 at 02:00
  • 1
    If you can explain *exactly* what you are trying to do then somebody may be able to provide a safe and reliable solution. – pjh Feb 16 '22 at 02:06