2015-10-06 85 views
0

我有這個字符串;終端/ Bash - 返回標籤

4.0K /Server/mysql/backup/backup_mysql_ltr_20151006-131057.tar.gz 

我只需要返回4.0K,但很明顯,這個數字可以是任何東西。我相信在K/Server之間有一個製表符

任何想法如何實現。它將用於Mac OS X和Ubuntu上的終端/ bash命令。

回答

2
<command that produces your output> | cut -f 1 

如果這不是K/Server之間的選項卡,然後

<command that produces your output> | cut -f 1 -d' ' 
+0

選擇這個一個作爲答案,因爲簡單。 – ajdi

1
s="4.0K /Server/mysql/backup/backup_mysql_ltr_20151006-131057.tar.gz" 
x="${s// *}" 
echo "$x" 

輸出:

 
4.0K 
+0

可能甚至是'echo'$ {s // [[:space:]] *}「',因爲OP提示標籤 – user000001

+0

感謝您提供這個有用的提示。 – Cyrus

+0

@Cyrus - 這個解決方案是否兼容所有的shell(sh,bash,ksh,csh,Tsh)? – sras

2

一種方法是隻使用awk

sz=$(echo "$string" | awk '{print $1}') 

按照以下轉錄物:

pax> string="4.0K /Server/blah_blah_blah.tar.gz" 
pax> sz=$(echo "$string" | awk '{print $1}') 
pax> echo $sz 
4.0K 

有使用cutsedgrep -o和許多其它方法等等(1)但我通常使用awk因爲:

  • 它自然適合於白色空間分離的領域;和
  • 它傾向於允許比其他更強大的編程。

(1)如:

sz=$(echo "$string" | cut -f1) 
sz=$(echo "$string" | sed 's/\t.*$//') 
sz=$(echo "$string" | grep -o $'^[^\t]*') 

等等...

+0

很好的回答!感謝(1)'替代選項! – ajdi