2016-01-22 136 views
0

我想製作一個腳本,它需要兩個參數,第一個是數字,第二個是字符串/文件列表。Shell腳本在兩個字符串之間顯示文本

listfile 3 test.txt test1.txt test2.txt 

基本上我想要做的就是把文件名稱下2個字符串<h></h>。就像這樣:

<h> 
test.txt 
test1.txt 
test2.txt 
</h> 

的東西,可以去那裏面的金額由這對於上面的例子是3

如果我運行像另一個例子是第一個參數確定:

listfile 1 test.txt test1.txt test2.txt 

在這種情況下,每個<h></h>可以容納1個文件。所以輸出會是這個樣子:

<h> 
test.txt 
</h> 
<h> 
test1.txt 
</h> 
<h> 
test2.txt 
</h> 

這裏是我的嘗試:

#!/bin/sh 

value=0 
arg1=$1 
shift 
for i in "[email protected]" 
do 
    if [ $value -eq 0 ]; then 
     echo "<h>" 
    fi 
    if [ $value -lt $arg1 ]; then 
     echo "$i" 
     value=`expr $value + 1` 
    fi 
    if [ $value -ge $arg1 ]; then 
     echo "</h>" 
     value=`expr $value - $value` 
    fi 
done 

到目前爲止,我得到它的工作,但唯一的問題是,過去</h>似乎沒有得到輸出我似乎無法找出解決方法。如果我嘗試:

listfile 4 test.txt test1.txt test2.txt 

它輸出,但缺少</h>

<h> 
test.txt 
test1.txt 
test2.txt 

如果誰能給我將非常感激的提示。

+0

'value = $(expr $ value - $ value)'更容易寫入'value = 0'。一個簡單的方法是在最後測試:如果值不爲零,則打印一個終止的'' –

回答

1
#!/bin/sh 

value=0 
arg1=$1 
shift 
echo "<h>" 
for i in "[email protected]" 
do 
    if [ $value -ge $arg1 ]; then 
     echo "</h>" 
     echo "<h>" 
     value=`expr $value - $value` 
    fi 
    echo "$i" 
    value=`expr $value + 1` 
done 
echo "</h>" 
0

我明白你想要完成什麼。您提供了一組具有前導數字的位置參數,並且您希望將<h>...</h>標籤之間的參數編號分組。

這是一種稍微不同於其他人採取的方法。已添加的檢查用於測試您的第一個位置參數是否提供了標籤之間其餘行的均勻分佈,並且如果行數不能均勻分配到該數字的組中,則會提供錯誤。

#!/bin/sh 

arg1="$1" 
shift 
nargs="$#" 
if [ $(((nargs - arg1) % arg1)) -ne 0 ] 
then 
    printf "error: arg1 provides unequal line distribution\n" 
    exit 1 
fi 
echo "<h>" 
for ((i = 1; i <= $nargs; i++)) 
do 
    echo "$1" 
    if [ $((i % arg1)) -eq 0 ] 
    then 
     if [ "$i" -lt "$nargs" ] 
     then 
      printf "</h>\n<h>\n" 
     else 
      printf "</h>\n" 
     fi 
    fi 
    shift 
done 

使用/輸出

$ sh outputh.sh 1 line.txt line1.txt line2.txt 
<h> 
line.txt 
</h> 
<h> 
line1.txt 
</h> 
<h> 
line2.txt 
</h> 

$ sh outputh.sh 2 line.txt line1.txt line2.txt 
error: arg1 provides unequal line distribution 

$ sh outputh.sh 3 line.txt line1.txt line2.txt 
<h> 
line.txt 
line1.txt 
line2.txt 
</h> 

注:,如果你想允許線的不平等分配的標籤之間,如:

$ sh outputh2.sh 2 line.txt line1.txt line2.txt 
<h> 
line.txt 
line1.txt 
</h> 
<h> 
line2.txt 
</h> 

然後一些額外的調整都是必需的。以下將允許所有分配 - 等於或不是:

#!/bin/sh 

closed=1 
arg1="$1" 
shift 
nargs="$#" 
echo "<h>" 
for ((i = 1; i <= $nargs; i++)) 
do 
    echo "$1" 
    if [ $((i % arg1)) -eq 0 ] 
    then 
     if [ "$i" -lt "$nargs" ] 
     then 
      printf "</h>\n<h>\n" 
      closed=1 
     else 
      printf "</h>\n" 
      closed=0 
     fi 
    fi 
    shift 
done 

if [ "$closed" -eq 1 ] 
then 
    echo "</h>" 
fi 
相關問題