2014-02-26 57 views
3

我寫一個簡單的腳本,拆分,通過使用下面的代碼保存一些文本的變量:劈裂的Unix文本

#!/bin/sh 

SAMPLE_TEXT=hello.world.testing 

echo $SAMPLE_TEXT 
OUT_VALUE=$SAMPLE_TEXT | cut -d'.' -f1 

echo output is $OUT_VALUE 

我期待輸出output is hello但是當我運行這個程序,然後我得到輸出爲output is。請讓我知道我在做什麼錯誤?

+2

'OUT_VALUE = $(回聲 「$ SAMPLE_TEXT」 |切-d - '' f1)'或更好,'OUT_VALUE = $(cut -d'。'-f1 <<<「$ SAMPLE_TEXT」)' – anishsane

回答

4

要評估命令並將其存儲到變量中,請使用var=$(command)

總之,你的代碼是這樣的:

SAMPLE_TEXT="hello.world.testing" 

echo "$SAMPLE_TEXT" 
OUT_VALUE=$(echo "$SAMPLE_TEXT" | cut -d'.' -f1) 
# OUT_VALUE=$(cut -d'.' -f1 <<< "$SAMPLE_TEXT") <--- alternatively 

echo "output is $OUT_VALUE" 

此外,請注意我周圍加上引號。這是一個很好的習慣,可以幫助你。


其他方法:

$ sed -r 's/([^\.]*).*/\1/g' <<< "$SAMPLE_TEXT" 
hello 

$ awk -F. '{print $1}' <<< "$SAMPLE_TEXT" 
hello 

$ echo "${SAMPLE_TEXT%%.*}" 
hello 
+1

非常感謝,它的工作。 – Chaitanya

4

答案由fedorqui是正確的答案。只需添加另一種方法......

$ SAMPLE_TEXT=hello.world.testing 
$ IFS=. read OUT_VALUE _ <<< "$SAMPLE_TEXT" 
$ echo output is $OUT_VALUE 
output is hello 
+0

這個答案並不是最好的方法,但使用'read -a'將字符串拆分爲數組非常有用。 – anishsane

+2

我認爲這是優越的,因爲它不需要額外的流程來處理'bash'可以做的事情。 – chepner

2

只是對@ anishane的評論擴展到了自己的答案:

$ SAMPLE_TEXT="hello world.this is.a test string" 
$ IFS=. read -ra words <<< "$SAMPLE_TEXT" 

$ printf "%s\n" "${words[@]}" 
hello world 
this is 
a test string 

$ for idx in "${!words[@]}"; do printf "%d\t%s\n" $idx "${words[idx]}"; done 
0 hello world 
1 this is 
2 a test string