簡體   English   中英

拆分字符串以打印前兩個由“ - ”分隔的字符。在Bash中

[英]Split a string to print first two characters delimited by “-” In Bash

我列出了AWS區域名稱。

us-east-1
ap-southeast-1

我想拆分字符串以打印特定的第一個字符-即“兩個字符” - “一個字符” - “一個字符”。 所以us-east-1應打印為use1ap-southeast-1應打印為aps1

我試過這個,它給了我預期的結果。 我在想是否有更短的方法來實現這一目標。

region=us-east-1 
regionlen=$(echo -n $region | wc -m) 
echo $region | sed 's/-//' | cut -c 1-3,expr $regionlen - 2-expr $regionlen - 1 

使用sed怎么樣:

echo "$region" | sed -E 's/^(.[^-]?)[^-]*-(.)[^-]*-(.).*$/\1\2\3/'

說明: s/pattern/replacement/命令選取區域名稱的相關部分,僅用相關位替換整個名稱。 模式是:

^         - the beginning of the string
(.[^-]?)  - the first character, and another (if it's not a dash)
[^-]*     - any more things up to a dash
-         - a dash (the first one)
(.)       - The first character of the second word
[^-]*-    - the rest of the second word, then the dash
(.)       - The first character of the third word
.*$       - Anything remaining through the end

括號中的位被捕獲,因此\\1\\2\\3將它們拉出來並用這些替換整個事物。

IFS影響參數擴展的字段分割步驟:

$ str=us-east-2
$ IFS=- eval 'set -- $str'
$ echo $#
3
$ echo $1
us
$ echo $2
east
$ echo $3

沒有外部工具; 只是用語言處理。

這就是1.13.4編寫的構建配置腳本如何解析版本號,如1.13.4和架構字符串,如i386-gnu-linux

如果我們保存並恢復IFS ,則可以避免eval

$ save_ifs=$IFS; set -- $str; IFS=$save_ifs

使用bash,並假設您需要區分西南和東南等事物:

s=ap-southwest-1

a=${s:0:2}
b=${s#*-}
b=${b%-*}
c=${s##*-}

bb=
case "$b" in
south*) bb+=s ;;&
north*) bb+=n ;;&
*east*) bb+=e ;;
*west*) bb+=w ;;
esac

echo "$a$bb$c"

怎么樣:

region="us-east-1"
echo "$region" | (IFS=- read -r a b c; echo "$a${b:0:1}${c:0:1}")
use1

一個簡單的sed -

$: printf "us-east-1\nap-southeast-1\n" |
     sed -E 's/-(.)[^-]*/\1/g'

為了保持noncardinal規范,比如southeast不同於south在添加一個可選的附加字符的成本-

$: printf "us-east-1\nap-southeast-1\n" |
   sed -E '
    s/north/n/;
    s/south/s/;
    s/east/e/;
    s/west/w/;
    s/-//g;'

如果你可以在south-southwest ,那么將g添加到那些方向減少。

如果你必須有4個字符的輸出,我建議將8或16個地圖方向映射到特定字符,這樣北方是N,東北方向可能是O和西北M ......那種東西。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM