linux下字符串操作,Linux Bash 中字符串操作
所謂“子字符串”就是出現(xiàn)在其它字符串內(nèi)的字符串。 比如 “3382” 就是 “this is a 3382 test” 的子字符串。 我們有多種方法可以從中把數(shù)字或指定部分字符串抽取出來。
本文會(huì)向你展示在 bash shell 中如何獲取或者說查找出子字符串。
在 Bash 中抽取子字符串
其語法為:
## 格式 ## ${parameter:offset:length}
子字符串?dāng)U展是 bash 的一項(xiàng)功能。它會(huì)擴(kuò)展成 parameter 值中以 offset 為開始,長為 length 個(gè)字符的字符串。 假設(shè), $u 定義如下:
## 定義變量 u ## u="this is a test"
那么下面參數(shù)的子字符串?dāng)U展會(huì)抽取出子字符串:
var="${u:10:4}" echo "${var}"
結(jié)果為:
test
其中這些參數(shù)分別表示:
10 : 偏移位置
4 : 長度
使用 IFS
根據(jù) bash 的 man 頁說明:
IFS (內(nèi)部字段分隔符)用于在擴(kuò)展后進(jìn)行單詞分割,并用內(nèi)建的 read 命令將行分割為詞。默認(rèn)值是。
另一種 POSIX 就緒POSIX ready的方案如下:
u="this is a test" set -- $u echo "$1" echo "$2" echo "$3" echo "$4"
輸出為:
this is a test
下面是一段 bash 代碼,用來從 Cloudflare cache 中去除帶主頁的 url。
#!/bin/bash
####################################################
## Author - Vivek Gite
## 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: $0 url1 url2 url3"; exit 1; }
## Get home page url as we have various sub dirs on domain
## /tips/
## /faq/
get_home_url(){ local u="$1" IFS='/' set -- $u echo "${1}${IFS}${IFS}${3}${IFS}${4}${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
它的使用方法為:
~/bin/cf.clear.cache https://www.cyberciti.biz/faq/bash-for-loop/ https://www.cyberciti.biz/tips/linux-security.html
借助 cut 命令
可以使用 cut 命令來將文件中每一行或者變量中的一部分刪掉。它的語法為:
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}"
想了解更多請(qǐng)閱讀 bash 的 man 頁:
man bash man cut
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的linux下字符串操作,Linux Bash 中字符串操作的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 面试官问我:平常如何对你的 Java 程
- 下一篇: 基于OpenDDS开发发布订阅Hello