2016-11-06 79 views
0

我需要创建Bash脚本,通过file050.txt生成名为file001.txt的文本文件 在这些文件中,所有文本都应该插入“This if xxx文件编号”(其中xxx是分配的文件编号),除了file007.txt,需要我为空。如何创建一个Bash脚本来创建包含文本的多个文件?

这是我迄今为止..

#!/bin/bash 

touch {001..050}.txt 

for f in {001..050} 

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

done 

不知道在哪里可以从这里走。任何帮助将非常感激。

+1

您是否尝试过使用循环内的'if'声明,或通过如下覆盖你所选择的文件(file007.txt)如'回声> file007.txt'的循环? –

+0

'touch'有什么意义?它只是重定向到文件中而没有做什么? –

回答

0

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> file慢得多(因为它启动了外部命令),并且不截断(所以如果文件已经存在,它将保留其内容)。您对该问题的文字描述表明您希望007.txt为空,从而使截断适当。
  • 使用C样式for循环,即。 for ((i=0; i<50; i++)),表示您可以使用变量作为最大数量;即。 for ((i=0; i<max; i++))。相反,您不能做{001..$max}。然而,这个确实需要的含义来在一个单独的步骤中添加零填充 - 因此printf
0
#!/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 
0

当然,你也可以costumize文件的名字和文本,关键的事情是${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 
相关问题