簡體   English   中英

重擊拆分子字符串

[英]Bash split substring

我有時收到帶有2的數字變量,有時收到的是3位數字,例如“ 321”和“ 32”。 我想在每個數字之間加一個點。 因此,如果接收到“ 32”,則必須回顯“ 3.2”,如果接收到“ 321”,則應回顯“ 3.2.1”。

這就是我做的:

S='321'
SL="${#S}" #string lentgh

n1=`echo $S | cut -c 1-1`
n2=`echo $S | cut -c 2-2`

if [ "$SL" -eq 2 ]; then
    echo $n1.$n2
elif  [ "$SL" -eq 3 ]; then
    n3=`echo $S | cut -c 3-3`
    echo $n1.$n2.$n3
else
    die 'Works only with 2 or 3 digits'
fi

我的問題是:做同一件事有沒有更短的方法?


更新:簡短但仍然冗長:

SL="${#1}" #string lentgh
S=$1
if [ "$1" -eq 3 ]; then
    $n3=".${S:2:1}"
fi
if  [ "$SL" -lt 2 ] && [ "$SL" -gt 3 ]; then
    die 'Works only with 2 or 3 digits'
fi

echo "${S:0:1}.${S:1:1}$n3"

更新1:

如果我包含if塊,則sed + regex版本將與純bash版本一樣長:

SL="${#1}" #string lentgh
S=$1
N=$(echo $S | sed -r "s/([0-9])/\1./g")
echo ${N%%.}
if  [ "$SL" -lt 2 ] && [ "$SL" -gt 3 ]; then
    die 'Works only with 2 or 3 digits'
fi

或者,將單行sed + regex與兩個表達式一起使用:

SL="${#1}" #string lentgh
echo $1 | sed -e 's/\([[:digit:]]\)/.\1/g' -e 's/^\.//'
if  [ "$SL" -lt 2 ] && [ "$SL" -gt 3 ]; then
    die 'Works only with 2 or 3 digits'
fi

謝謝。

這是一個。 這將適用於任何字符串長度。

#!/bin/bash

#s is the string
#fs is the final string

echo "Enter string"
read s

n="${#s}"
fs=""

i=0
for ((i=0; i<n; i++))
  do
   fs="$fs.${s:i:1}"
done

#find the length of the final string and
#remove the leading '.' 

n="${#fs}"
fs="${fs:1}"

echo "$fs"

它不是那么漂亮,但至少很短:

num=$(echo $S | sed -r "s/([0-9])/\1./g")
echo ${num%%.}

我也更喜歡sed:

echo 321 | sed -e 's/\\([[:digit:]]\\)/.\\1/g' | cut -b2- echo 321 | sed -e 's/\\([[:digit:]]\\)/.\\1/g' | cut -b2- --> 3.2.1

echo 32 | sed -e 's/\\([[:digit:]]\\)/.\\1/g' | cut -b2- echo 32 | sed -e 's/\\([[:digit:]]\\)/.\\1/g' | cut -b2- --> 3.2

還是沒有切成這樣

echo 321 | sed -e 's/\([[:digit:]]\)/.\1/g' -e 's/^\.//'
S='321'
perl -e "print join '.', split //, shift" "$S"

暫無
暫無

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

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