[英]to pass output of a command to a variable in shell script
我試圖將命令的輸出傳遞給變量。 試過很多報價但沒有成功,請檢查
我正在讀取$ line中的文件輸入並處理它,試圖將輸出保存在變量a中。
set a="$($line|cut -d'-' -f 2|cut -d'.' -f 1|sed 's/[^0-9]*//g’)"
一些東西。
第一個是你不應該使用set
,那是shell變量而不是環境變量。
其次,除非$line
是實際命令 ,否則你需要回應它。
第三,你對sed
命令的結束引用是錯誤的類型, '
而不是'
。
所以,你應該使用:
a="$(echo $line|cut -d'-' -f 2|cut -d'.' -f 1|sed 's/[^0-9]*//g')"
您可以在以下記錄中看到這一點:
pax> line="date=2014.09.05-time=12.34.56"
pax> a="$(echo $line|cut -d'-' -f 2|cut -d'.' -f 1|sed 's/[^0-9]*//g')"
pax> echo $a
12
其抓住第二-
分隔場( time=12.34.56
),則第一.
從那個分隔的字段( time=12
),然后在開始時剝離所有非數字,只給12
。
使用echo
a="$(echo $line|cut -d'-' -f 2|cut -d'.' -f 1|sed 's/[^0-9]*//g')"
假設$filename
是$filename
的名稱,你正在閱讀,你幾乎就在那里:
a="$(<$filename cut -d'-' -f 2|cut -d'.' -f 1|sed 's/[^0-9]*//g')"
問題是:
set
,這沒有用 $line
) 執行它,你想從中讀取。 //g
之后錯誤的引用 - 你想要一個簡單的單引號( '
) 而不是使用長的多進程管道,而是使用shell本身提供的參數擴展工具。
tmp1=${line#*-} # Remove everything up to and include the first -
tmp2=${tmp1%%.*} # Remove everything from the first . onward
a=${tmp2//[!0-9]} # Remove anything that isn't a numerical digit
如果您正在讀取文件,則可以將第一步折疊到讀取命令本身
while IFS=- read first second rest; do
tmp=${second%%.*}
a=${tmp//[!0-9]}
done
定義一個正則表達式來捕獲你想要的字符串部分也可能更簡單(一個示例行將有助於定義這樣的正則表達式)。
[[ $line =~ $regex ]] && a=${BASH_REMATCH[1]} # Assuming the first capture group
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.