0

I am new to shell scripting and I can't figure it out on how to check the filenames if it has a specific string.

For example, the filenames are in xyz.abc.d.CSV format. How can I check if the filename contains that string?

Here is my code:

ls *.CSV | while read filename; do 
    if [ filename == "*abc*"]; then
        echo "Found it" 
    else
        echo "No abc"
done

ls *.CSV list all the files with a .csv format. while reading the files, the code will compare if the filename have an "abc" string. if yes, the system will print "Found it", else, the system will print "No abc".

5
  • You can use grep command for that. Commented Oct 18, 2018 at 11:53
  • Why do you need this big loop for a simple grep statement? Check this ls *.CSV | grep -E "abc" Commented Oct 18, 2018 at 11:56
  • Thank you @aicastell for your help :) Commented Oct 18, 2018 at 12:07
  • Thank you @AmitBhardwaj for your help :) Commented Oct 18, 2018 at 12:08
  • 2
    Use echo *.CSV instead of ls. Commented Oct 18, 2018 at 12:27

1 Answer 1

1

No need for any loop. Just let the shell do the heavy lifting:

ls *abc*.CSV
Sign up to request clarification or add additional context in comments.

2 Comments

@Aleeza please also remove the ls and read part. It's unnecessarily complicated and unsafe. Just for filename in *abc*.CSV; do ... will do.
At least for the purpose indicated in the question, if ls *abc*.CSV > /dev/null; then is probably the simplest thing to do. You don't actually care about the output, only the exit status, of ls. (Echoing the same, filename-agnostic string for each match seems pointless. Use the loop if there's actually something specific for each filename to do.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.