【问题标题】:How can I create a Bash script that creates multiple files with text, excluding one?如何创建一个 Bash 脚本来创建多个带有文本的文件,不包括一个?
【发布时间】:2016-11-06 19:24:19
【问题描述】:

我需要创建通过 file050.txt 生成名为 file001.txt 的文本文件的 Bash 脚本 在这些文件中,除了 file007.txt 需要我为空之外,所有文件都应该插入“This if file number xxx”(其中 xxx 是分配的文件号)。

这是我目前所拥有的......

#!/bin/bash

touch {001..050}.txt

for f in {001..050}

do
    echo This is file number > "$f.txt"

done

不知道从这里去哪里。任何帮助将不胜感激。

【问题讨论】:

  • 您是否尝试过在循环中使用if 语句,或者通过覆盖您选择的文件(file007.txt)来跟随循环,例如echo > file007.txt
  • touch 的意义何在?只是重定向到文件中没有做什么?

标签: bash


【解决方案1】:
#!/bin/bash

for f in {001..050}
do
    if [[ ${f} == "007" ]]
    then
        # creates empty file
        touch "${f}.txt"
    else
        # creates + inserts text into file
        echo "some text/file" > "${f}.txt"
    fi

done

【讨论】:

    【解决方案2】:

    continue 语句可用于跳过循环的迭代并继续下一个循环——尽管您实际上确实想要对文件 7 进行操作(创建它) , 有一个条件同样有意义:

    for (( i=1; i<50; i++ )); do
      printf -v filename '%03d.txt' "$i"
      if (( i == 7 )); then
        # create file if it doesn't exist, truncate if it does
        >"$filename"
      else
        echo "This is file number $i" >"$filename"
      fi
    done
    

    这里说一下具体的实施决策:

    • 使用touch file&gt; file 慢得多(因为它启动一个外部命令),并且不会截断(所以如果文件已经存在,它将保留其内容);您对问题的文字描述表明您希望 007.txt 为空,从而适当地进行截断。
    • 使用 C 风格的for 循环,即。 for ((i=0; i&lt;50; i++)),表示你可以使用一个变量作为最大数; IE。 for ((i=0; i&lt;max; i++))。相比之下,你不能做{001..$max}。然而,这确实需要在单独的步骤中添加零填充——因此printf

    【讨论】:

      【解决方案3】:

      当然,你可以自定义文件名和文本,关键是${i}。我试图说清楚,但如果您有不明白的地方,请告诉我们。

      #!/bin/bash
      # Looping through 001 to 050
      for i in {001..050}
      do
          if [ ${i} == 007 ]
          then
              # Create an empty file if the "i" is 007
              echo > "file${i}.txt"
          else
              # Else create a file ("file012.txt" for example)
              # with the text "This is file number 012" 
              echo "This is file number ${i}" > "file${i}.txt"
          fi
      done
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-12-07
        • 1970-01-01
        • 2017-01-26
        • 2020-05-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多