如何使用bash从URL字符串获取尺寸 [英] How to get dimensions from URL string using bash

查看:79
本文介绍了如何使用bash从URL字符串获取尺寸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Mac上使用bash,并且有一个URL字符串,我想从包含以下任何尺寸的URL中提取宽度和高度值:

I am using bash on mac and have a URL string that I want to extract the width and height values from a url containing dimensions like any of below:

url=domain.com/project/asset_300x250_july2/
url=domain.com/project/300x250_asset_july2/
url=domain.com/project/asset_300x250/

我认为我需要搜索出现在"x"之前的数字,然后搜索出现在"x"之后的数字.有一个简单的方法来做到这一点吗?与此类似,仅提取所有数字:

I figure I need to search for occurrences of numbers before the 'x', and then numbers after 'x'. Is there an easy way to get this? Something similar to this, which only extracts all the numbers:

width="${url//[!0-9]/}"

推荐答案

您为此任务定义了一个正则表达式.假设尺寸遵循问题[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]}" ; }

这篇关于如何使用bash从URL字符串获取尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆