how to use command line argument to find .txt file that have common name

I have multiple files in a directory called files. I have to read each .txt file from this directory:

abc123.txt
abc234.txt
abc345.txt
abc.txt
def123.txt
def234.txt
def345.txt

For example, when I type ./filter.sh abc in the terminal, it will search for the .txt file whose name contains abc.

#!/bin/bash
 
input1=$1


find ./files -type f -name "*$input1*.txt" 

my output look like this

./files/abc345.txt
./files/abc234.txt
./files/abc123.txt
./files/abc.txt

am I doing it correctly? And also, is it possible not to show ./files/ in the output? And why does my output show abc345, abc234, abc123 instead of abc123, abc234, abc345?


Solution 1:

  • Yes, it is good. But when you get more familiar with find, you will do it directly on the command line (instead of via a shellscript). I use shellscripts a lot, but mainly for bigger tasks (several command lines).

  • You can strip the starting-point under which it was found:

    find ./files -type f -name "*$input1*.txt" -printf "%P\n"
    
  • Finally you can sort the files afterwards:

    find ./files -type f -name "*$input1*.txt" -printf "%P\n" | sort
    
  • If a small number or small files you can write the content to the terminal with

    find ./files -type f -name "*$input1*.txt" -exec echo "--- {}:" \; -exec cat {} \;
    

    The output can be redirected to a file by > output.txt

    find ./files -type f -name "*$input1*.txt" -exec echo "--- {}:" \; -exec cat {} \; > output.txt
    

    Scroll horizontally to see the end of this line.

  • if many files or some big file, it may be better to view the files in less or maybe your favourite text editor,

    find ./files -type f -name "*$input1*.txt" -exec less {} \;
    

    and exit with 'q' from less between each file.

  • find versus ls

    • find is an advanced tool that can find files [recursively] in a directory tree, and it has many options. It takes a long time to learn what can be done with it. See man find or maybe easier, see a tutorial via the internet.

    • ls is a simpler tool, that lists files at one directory level, usually the current level. It has also many options, but is quite easy to use from the command line. Please be aware, that ls can behave in a confusing way in shellscripts, particularly in combinations with other commands. See man ls.

Solution 2:

You can do it like that and follow @sudodus advice to improve the output.

However find is a bit an overkill for your use case, you could simply use ls:

ls -1 files/abc*

To get of the directory name:

(cd files && ls -1 abc*)