2016-11-06 81 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 
相關問題