如何突出显示生成的数字序列中的给定值?

How can I highlight given values in a generated numeric sequence?

我经常收到文档 ID 的无序列表。我可以很容易地对它们进行排序和打印,但我想为每个可用文档打印一行,并在给定列表中的所有值旁边显示一个星号(或任何东西,只是为了突出显示)。

比如...

$ ./t.sh "1,4,3" 5

1*
2
3*
4*
5

$

第一个参数是无序列表,第二个参数是文档总数。

以下代码适用于您的示例。

  1. 生成用户给定长度的序列
  2. 拆分脚本的第一个参数(例如,它会给你一个数组 A
  3. 使用函数contains检查A中的一个元素是否在第一步生成的序列中

我不检查参数长度,您应该检查参数长度以获得更合适的脚本。

#!/bin/bash

function contains() {
    local n=$#
    local value=${!n}
    for ((i=1;i < $#;i++)) {
        if [ "${!i}" == "${value}" ]; then
            echo "y"
            return 0
        fi
    }
    echo "n"
    return 1
}

IFS=', ' read -a array <<< 

for i in $(seq ); do
    if [ $(contains "${array[@]}" "${i}") == "y" ]; then
        echo "${i}*"
    else
        echo "${i}"
    fi
done

如果 "available document" 是指 "existing file on disk",那么假设您总共有 5 个文件,并且您正在检查是否有 1、4 和 3。以下脚本将生成 sorted输出。

#!/bin/bash

#Store the original IFS
ORGIFS=$IFS
#Now Set the Internal File Separater to a comma
IFS=","

###Identify which elements of the array we do have and store the results
### in a separate array
#Begin a loop to process each array element
for X in  ; do
        if [[ -f ${X} ]] ; then
                vHAVE[$X]=YES
        fi
done


#Now restore IFS
IFS=$ORGIFS

#Process the sequence of documents, starting at 1 and ending at .
for Y in $(seq 1 1 ) ; do
        #Check if the sequence exists in our inventoried array and mark accordingly.
       if [[ ${vHAVE[$Y]} == YES ]] ; then
                echo "$Y*"
        else
                echo "$Y"
        fi
done

Returns 结果:

rtcg@testserver:/temp/test# ls
rtcg@testserver:/temp/test# touch 1 3 4
rtcg@testserver:/temp/test# /usr/local/bin/t "1,4,3" 5
1*
2
3*
4*
5

您可以使用参数替换来构建扩展模式,该模式可用于将文档编号与要标记的文档列表相匹配。

#!/bin/bash

# 1,4,3 -> 1|4|3
to_mark=${1//,/|}
for(( doc=1; doc <= ; doc++)); do
    # @(1|4|3) matches 1, 4 or 3
    printf "%s%s\n" "$doc" "$( [[ $doc = @($to_mark) ]] && printf "*" )"
done