gpt4 book ai didi

bash - If 条件下不区分大小写的比较

转载 作者:行者123 更新时间:2023-11-29 09:02:47 25 4
gpt4 key购买 nike

我有这个 csv 文件,我需要计算满足行条目在特定年份范围之间且艺术家名称与名称参数匹配的条件的行数。但是字符串匹配应该不区分大小写。我如何在 if 循环中实现它..

我是初学者,请多多包涵

#!/bin/bash

file="$1"
artist="$2"
from_year="$(($3-1))"
to_year="$(($4+1))"
count=0

while IFS="," read arr1 arr2 arr3 arr4 arr5 arr6 arr7 arr8 arr9 arr10 arr11 ; do

if [[ $arr11 -gt $from_year ]] && [[ $arr11 -lt $to_year ]] && [[ $arr7 =~ $artist ]]; then
count=$((count+1))
fi

done < "$file"
echo $count

$arr7 =~ $artist 部分是我需要修改的地方

最佳答案

Bash 有一个将字符串转换为小写的内置方法。一旦它们都是小写字母,您就可以比较它们是否相等。例如:

$ arr7="Rolling Stones"
$ artist="rolling stoneS"
$ [ "${arr7,,}" = "${artist,,}" ] && echo "Matches!"
Matches!
$ [[ ${arr7,,} =~ ${artist,,} ]] && echo "Matches!"
Matches!

详情

${parameter,,} 将字符串中的所有字符转换为小写。如果要转换为大写,请使用 ${parameter^^}。如果只想转换部分字符,请使用 ${parameter,,pattern},其中只有那些匹配 pattern 的字符会被更改。 manbash` 记录了关于这方面的更多细节:

${parameter^pattern}
${parameter^^pattern}
${parameter,pattern}
${parameter,,pattern}

Case modification. This expansion modifies the case of alphabetic characters in parameter. The pattern is expanded to produce a pattern just as in pathname expansion. The ^ operator converts lowercase letters matching pattern to uppercase; the , operator converts matching uppercase letters to lowercase. The ^^ and ,, expansions convert each matched character in the expanded value; the ^ and , expansions match and convert only the first character in the expanded value. If pattern is omitted, it is treated like a ?, which matches every character. If parameter is @ or *, the case modification operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with @ or *, the case modification operation is applied to each member of the array in turn, and the expansion is the resultant list.

兼容性

这些大小写修改方法需要 bash 版本 4(2009 年 2 月 20 日发布)或更高版本。

关于bash - If 条件下不区分大小写的比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26320553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com