如何在Bash中提取子字符串
时间:2020-01-09 14:17:07 来源:igfitidea点击:
我有一个bash shell变量,u="this is a test"
如何提取测试字符串并存储到shell变量中?
子字符串什么都不是,但是字符串是其中出现的字符串。
例如3382是"3382 test"中的一个子字符串 。
可以使用各种方法来提取数字或给定的字符串。
本快速教程介绍了使用bash shell时如何获取或查找子字符串。
在Bash中提取子字符串
语法为:
## syntax ##
${parameter:offset:length}
子字符串扩展是一项bash功能。
它可以扩展到参数值的最大长度字符,从offset指定的字符开始。
例如,$u定义如下:
## define var named u ## u="this is a test"
以下子字符串参数扩展执行子字符串提取:
var="${u:10:4}"
echo "${var}"
输出示例:
test
数字代表的地方
- 10:偏移
- 4:长度
使用IFS
从bash手册页:
内部字段分隔符,用于在扩展后进行单词拆分,并使用read Builtin命令将行拆分为单词。
默认值为<space> <tab> <newline>。
另一个支持POSIX的解决方案如下:
u="this is a test" set -- $u echo "" echo "" echo "" echo ""
输出示例:
this is a test
这是一个bash代码,可从Cloudflare缓存和主页中清除网址:
#!/bin/bash
####################################################
## Author - {https://www.theitroad.local/}
## Purpose - Purge CF cache
## License - Under GPL ver 3.x+
####################################################
## set me first ##
zone_id="YOUR_ZONE_ID_HERE"
api_key="YOUR_API_KEY_HERE"
email_id="YOUR_EMAIL_ID_HERE"
## hold data ##
home_url=""
amp_url=""
urls="$@"
## Show usage
[ "$urls" == "" ] && { echo "Usage: ~/bin/cf.clear.cache https://www.theitroad.local/faq/bash-for-loop/ https://www.theitroad.local/tips/linux-security.html
url1 url2 url3"; exit 1; }
## Get home page url as we have various sub dirs on domain
## /tips/
## /faq/
get_home_url(){
local u=""
IFS='/'
set -- $u
echo "${IFS}${IFS}${IFS}${IFS}"
}
echo
echo "Purging cache from Cloudflare..."
echo
for u in $urls
do
home_url="$(get_home_url $u)"
amp_url="${u}amp/"
curl -X DELETE "https://api.cloudflare.com/client/v4/zones/${zone_id}/purge_cache" \
-H "X-Auth-Email: ${email_id}" \
-H "X-Auth-Key: ${api_key}" \
-H "Content-Type: application/json" \
--data "{\"files\":[\"${u}\",\"${amp_url}\",\"${home_url}\"]}"
echo
done
echo
我可以如下运行:
u="this is a test"
echo "$u" | cut -d' ' -f 4
echo "$u" | cut --delimiter=' ' --fields=4
##########################################
## WHERE
## -d' ' : Use a whitespace as delimiter
## -f 4 : Select only 4th field
##########################################
var="$(cut -d' ' -f 4 <<< $u)"
echo "${var}"
cut命令
可以使用cut命令从文件或变量的每一行中删除节。
语法为:

