bash
2017-03-03 56 views 0 likes 
0

一個字符串,我需要在bash解析字符串的一部分:解析在bash

#string1=$(grep "build_no" /etc/build_file) 
#val=$(echo $string1 | cut -d'=' -f 2) 
#echo $val 
"7.6.0-custom-build" 

從上面的字符串,我希望能夠提取「7.6.0」。所以我做:

#current_build=$(echo $val | cut -d'-' -f 1) 

但收盤報價缺少結尾:

#echo $current_build 
"7.6.0 

我該如何解決這個問題?

另外,如果我有另一個變量:

#echo $other_build 
"7.1.0" 

我可以比較兩個具有發現兩者的更高建立如下的意圖是什麼?

#if [ "$current_build" \< "$other_build" ]; then 
... 
#else 
... 
#fi 

謝謝!

+0

雙引號是作爲字符串的一部分來存放還是隻存儲在變量中? – Inian

+0

[在Bash中如何比較兩個字符串以點分隔的版本格式?](http://stackoverflow.com/questions/4023830/how-compare-two-strings-in-dot-separated-version-format-in -bash) – Inian

+0

@Inian:引號是字符串的一部分。 – Maddy

回答

0

你可以試試這個 -

var1="7.6.0" 
var2="7.1.0" 
awk -v var1="$var1" -v var2="$var2" 'BEGIN{ if(var1 > var2) {print "higher"} else {print "lower"}}' 
higher 
0

如果你的輸入字符串可能含有應該從開頭和結尾被剝去各種非數字的文物,你可以使用這樣的事情。

clean_numeric() { 
    local trim 
    local value 
    trim=${1%%[0-9]*} 
    value=${1#$trim} 
    trim=${value##*[0-9]} 
    value=${value%$trim} 
    case $value in 
     *[!-0-9.]*) 
     echo "clean_numeric: invalid input $1" >&2 
     return 1 ;; 
    esac 
    echo "$value" 
} 

這是一個通用的功能,你可以在東西叫像

string1=$(grep "build_no" /etc/build_file) 
#val=$(echo $string1 | cut -d'=' -f 2) 
val=${string1#*=} 
final=$(clean_numeric "${val%%-*}") 

通知偏愛使用shell的內置的字符串替換功能,這既是更簡潔,更高效(和更容易理解,一旦你熟悉語法),而不是使用外部進程進行微不足道的替換。

您似乎在問如果缺少某個引號時會添加引號,但將數字規範化爲數字(然後如果您真的需要,則將引號加回數字)似乎更簡單且更易於管理。

0

您可以在sed類替代語法使用Perl和實現任何你需要使用Perl的正則表達式分組:

$ echo "$a" 
"7.6.0-custom-build" 

$ perl -pe 's/(^.)(.*?)-(.*?)(.$)/\1\2\4/' <<<"$a" 
"7.6.0" 
#Input string is divided in groups : 
#1st group contains the first character " or ' or whatever it is. 
#2nd group match any char for zero or more times in use with the "non-greedy operator `?`" 
#4th group match the end of line with the previous char (either " or ' or whatever 
#The whole input string is replaced by group 1-2-4 

$ perl -pe 's/(^.)(.*?)-(.*?)(.$)/\2/' <<<"$a" 
7.6.0 
# Similarly , without the 1st and last chars = only group2 

$ perl -pe 's/(^.)(.*?)-(.*?)(.$)/\2/;s/[.-]//g' <<<"$a" 
760 
#Like before but with an extra substitution to remove literal dots or dashes that use to exist in version. 

有了上次的命令,你可以將任何字符串代表一個版本號爲平號:
7.6.0760
7.1.0710

因此,你可以直接比較它們與慶典整數-gt/-lt運營商。

包括破折號在最後一個例子,你也可以轉換的版本,如:
7.6.1-17611

PS:我喜歡perl -pesed因爲:
(一)perl的支持非貪婪的正則表達式時的sed不支持

(B)的Perl系列取代指的是先前變換的文本,而在sed每個替換指的是初始 - 傳入文本/流

(c)Perl將在所有系統中以同樣的方式工作,即他們已安裝perl(即Debian,BSD,MAC,無論何處),並使其完全便攜。

相關問題