简体   繁体   English

Shell脚本嵌套循环

[英]Shell script nested loop

I want to produce a list of files between 14 and 22 April. 我想提供4月14日至22日之间的文件列表。
The filenames will have the date in the name, eg J0018658.WANCL90A.16Apr2014.214001.STD.txt . 文件名中的日期将带有名称,例如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. 我在AIX上使用它,默认的shell是ksh。 However sh and bash are also available. 但是,也可以使用sh和bash。 Here is what works with ksh: 这是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: 这是使用bash更好的方法:

#!/bin/bash

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

will try to expand a variable called iApr , which is not what you want. 将尝试扩展名为iApr的变量,这不是您想要的。

Instead, try making your inner for loop look like this: 相反,请尝试使您的内部for循环看起来像这样:

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

Also, your outer loop can be similar to the concept in @anubhava's answer: 另外,您的外循环可以类似于@anubhava的答案中的概念:

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 再次感谢@anubhava指出shopt -s nullglob的必要性


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

If you're running Linux, your /bin/sh is likely simply a symlink to /bin/bash . 如果您正在运行Linux,则/bin/sh可能只是与/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. 如果使用名称sh调用bash,则它将尝试尽可能接近于sh的历史版本的启动行为,同时也要符合POSIX标准。

You can do: 你可以做:

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

OR in BASH: 或以重击形式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM