Shell 脚本显示两个字符串之间的文本

Shell script display text in between two strings

我正在尝试制作一个带有两个参数的脚本,第一个是数字,第二个是 strings/files 的列表。

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=
shift
for i in "$@"
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

如果有人能给我一个提示,我将不胜感激。

#!/bin/sh

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

我明白你想完成什么。您提供了一组带有前导数字的位置参数,并且您希望在 <h>...</h> 标签之间对该数量的参数进行分组。

这里采用的方法与其他方法略有不同。已添加检查以测试您的第一个位置参数是否提供标记之间剩余行的均匀分布,如果行数不能均匀地分为该数字的组,则会提供错误。

#!/bin/sh

arg1=""
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 ""
    if [ $((i % arg1)) -eq 0 ]
    then
        if [ "$i" -lt "$nargs" ]
        then
            printf "</h>\n<h>\n"
        else
            printf "</h>\n"
        fi
    fi
    shift
done

Use/Output

$ 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=""
shift
nargs="$#"
echo "<h>"
for ((i = 1; i <= $nargs; i++))
do
    echo ""
    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