在 csh 腳本中使用檔案輸入變數

在 csh 腳本中使用檔案輸入變數
unix%:~/tmp$ cat tmp.txt 
z=0.016728
NH=5.7E20
Center for spectra: 2:00:14.906, +31:25:45.826

我希望將 的值z設為名為 的變量$redsh,將 的值NH設為$abun,並將中心的值設為$xc$yc

我該怎麼做呢?

答案1

我會用來sed替換文件中的值,添加set並運行eval整個文件:

eval `sed 's/z=/set redsh=/;s/NH=/abun=/;s/.*: \(.*\), \(.*\)/xc=\1 yc=\2/' tmp.txt`

運行範例

% unset redsh abun xc yc
% cat tmp.txt
z=0.016728
NH=5.7E20
Center for spectra: 2:00:14.906, +31:25:45.826
% eval `sed 's/z=/set redsh=/;s/NH=/abun=/;s/.*: \(.*\), \(.*\)/xc=\1 yc=\2/' tmp.txt`
% set
abun    5.7E20
redsh   0.016728
xc      2:00:14.906
yc      +31:25:45.826

但請注意:您不應該使用 C shell。使用 Bourne shell。

答案2

閱讀man csh;man grep;man cut;man awk;man tr並做類似的事情

set redsh = "`grep -E '^z=' tmp.txt | cut -d= -f2`"
set abun = "`grep -E '^NH=' tmp.txt | cut -d= -f2`"
set xc = "`grep -E '^Center for spectra: ' tmp.txt | cut -d, -f1 | cut '-d ' -f4`"
set yc = "`grep -E '^Center for spectra: ' tmp.txt | cut -d, -f2 | tr -d ' '`"

相關內容