遍历字符串数组,并在Bash中删除它们的部分值?

[英]Iterating through an array of strings, and removing parts of their values in Bash?


How to iterate through an array of strings, and remove parts of their values? (BASH)

如何遍历字符串数组,并删除它们的部分值?(BASH)

I have an array populated with a list of sites saved as strings, and I want to grab the sections of them that are to the left of '.com.au' and save them to a new array. There are also a couple of items in the string that don't end with '.com.au' and I want to ignore them completely.

我有一个以字符串形式保存的站点列表填充的数组,我想抓取其中位于“。com.au”左边的部分,并将它们保存到一个新的数组中。字符串中也有一些条目没有以“。com.au”结尾,我想完全忽略它们。

To make it a bit easier to read, I've removed most of the code and only left in what I think will be relevant to the question:

为了便于阅读,我删除了大部分代码,只留下了我认为与问题相关的内容:

#!/bin/bash
full_array(*); declare -p full_array
edited_array=()

for x in ${full_array[@]};
    #If x ends with '.com.au'
        #Remove '.com.au' from x
        #Save output to edited_array
    #Else
        #Skip item
done

Will I have to use regex to do this? If so, does anyone know of any good tutorials online that would be worth checking out?

我必须使用regex来做这个吗?如果是的话,有没有人知道有什么好的在线教程值得一看?

2 个解决方案

#1


2  

This should work:

这应该工作:

for x in ${full_array[@]};do
[[ $x == *.com.au ]] && edited_array+=("${x%.com.au}")
done

#2


1  

if [[ $x == *.com.au ]]; then
    edited_array+=( "${x%.com.au}" )
fi

Inside bash double brackets, the == operator is a pattern-matching operator. Then, just use shell parameter expansion to remove the domain and append to the array with +=

在bash双括号内,==操作符是一个模式匹配操作符。然后,只需使用shell参数展开来删除域并将+=附加到数组中


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2015/05/04/7f06624fecc055bf96e719ff902d0aa1.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号