且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用bash从URL字符串获取尺寸

更新时间:2023-02-24 09:30:20

您为此任务定义了一个正则表达式.假设尺寸遵循问题[0-9]x[0-9]中的语法,则可以执行以下操作.

You define a regex for such a task. Assuming your dimensions follow the syntax as in the question [0-9]x[0-9] you can do something like below.

bash中的正则表达式支持允许匹配和捕获字符串,这些字符串将填充在数组BASH_REMATCH中.匹配元素的索引从1开始

The regex support in bash allows to match and capture strings, which will be populated in the array BASH_REMATCH. The index of the matched elements start from 1

适当的脚本可以按如下方式详细编写.

A proper script could be written in detail as below.

#!/usr/bin/env bash

regex='([[:digit:]]{1,})x([[:digit:]]{1,}).*$'

if [[ $url =~ $regex ]]; then
    printf '%s x %s\n' "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}"
fi

要做一个命令行友好的版本

A command-line friendly version of it would be to do

[[ $url =~ $regex ]] && { width="${BASH_REMATCH[1]}"; height="${BASH_REMATCH[2]}" ; }