我寫一個簡單的腳本,拆分,通過使用下面的代碼保存一些文本的變量:劈裂的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
。請讓我知道我在做什麼錯誤?
我寫一個簡單的腳本,拆分,通過使用下面的代碼保存一些文本的變量:劈裂的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
。請讓我知道我在做什麼錯誤?
要評估命令並將其存儲到變量中,請使用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
非常感謝,它的工作。 – Chaitanya
只是對@ 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
'OUT_VALUE = $(回聲 「$ SAMPLE_TEXT」 |切-d - '' f1)'或更好,'OUT_VALUE = $(cut -d'。'-f1 <<<「$ SAMPLE_TEXT」)' – anishsane