0

I want to produce a list of files between 14 and 22 April.
The filenames will have the date in the name, e.g. J0018658.WANCL90A.16Apr2014.214001.STD.txt.
I have tried this script.

for i in 14 15 16 17 18 19 20 21 22; do
    for x in *$iApr*.txt; do
      echo "$x"
    done
done

I am using this on AIX and the default shell is ksh. However sh and bash are also available. Here is what works with ksh:

for i in 14 15 16 17 18 19 20 21 22; do
    for x in *${i}Apr*.txt; do
        echo "$x"
    done
done

Here is what works even better with bash:

#!/bin/bash

shopt -s nullglob
for i in {14..22}; do
    for x in *${i}Apr*.txt; do
          echo "$x"
    done
done

2 Answers 2

3

will try to expand a variable called iApr, which is not what you want.

Instead, try making your inner for loop look like this:

for x in *${i}Apr*.txt; do

Also, your outer loop can be similar to the concept in @anubhava's answer:

for i in {14..22}; do

So the script should look something like this:

#!/bin/bash

shopt -s nullglob
for i in {14..22}; do
    for x in *${i}Apr*.txt; do
          echo "$x"
    done
done

Again, thanks @anubhava for pointing out the necessity of shopt -s nullglob


About #!/bin/sh vs. #!/bin/bash:

If you're running Linux, your /bin/sh is likely simply a symlink to /bin/bash. From the man page:

If bash is invoked with the name sh, it tries to mimic the startup behavior of historical versions of sh as closely as possible, while conforming to the POSIX standard as well.

Sign up to request clarification or add additional context in comments.

5 Comments

Script now looks like:for i in {14..22}; do for x in *${i}Apr*.txt; do echo "$x" done done However the output is just *{14..22}Apr*.txt done
Which version of bash are you using? Do you have !#/bin/bash or #!/bin/sh at the top of the script? You'll need at least version 3.2 and !#/bin/bash to do the {14..22} expansion.
I guess my sh is too old. I switched to /bin/bash and it works. Thanks
@BrianG see my note about #!/bin/sh vs. #!/bin/bash
Thanks for the info about sh vs bash. I am actually using AIX and the default shell is ksh, but sh and bash are both available.
2

You can do:

ls *{14..22}Apr*.txt

OR in BASH:

shopt -s nullglob; echo *{14..22}Apr*.txt

Comments

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.