簡體   English   中英

如何將實用程序的返回值(grep / sed)分配給數組?

[英]How do you assign the return value of a utility (grep/sed) to an array?

我正在嘗試創建一個Shell腳本來制作一個Makefile。 我的策略是創建兩個數組,一個包含所有.cpp文件,另一個包含.cpp后綴替換為.o。 然后,我將(grep | sed)的返回值中的.h和.ccp文件分配給變量temp,然后打印數組。 但是,我不斷收到錯誤消息:“語法錯誤:無效的算術運算符(錯誤令牌為“ .o”)我的理論是grep的返回值未正確存儲在temp中,我對bash還是很陌生

cppfield=$(ls *.cpp)
x=0
for i in *.cpp; do
  ofield[$x]="${i%.cpp}.o"
done


echo "$1 : ${ofield[@]}" > Makefile
echo "  g++ -ansi -Wall -g -o $1 ${ofield[@]}" >> Makefile

for i in "${ofield[@]}"; do
  temp=$(grep '#include "' ${cppfield[i]} | sed s/#include// | sed s/\"//g)
  echo "${ofield[i]} : ${cppfield[i]} ${temp[@]}" >> Makefile
  echo "    g++ -ansi -Wall -g -c ${cppfield[i]}" >> Makefile
done

您要嘗試做的是找到依賴項,這可能是g++ -MM更好的方法-它為您指定的文件生成一個依賴項列表,您可以在makefile中包含/使用該文件。

參見此文件的底部,我的makefile通常包含以下內容:

include .depends

.depends: Makefile ${SOURCES}
    ${CXX} -MM ${CXXFLAGS} ${SOURCES} > $@

完整檔案: https : //github.com/Leporacanthicus/lacsap/blob/master/Makefile

在執行以下操作之前,您的grep解決方案相當有效:

 #if _WIN32
 #include <windows.h>
 #else
 #include <someother.h>
 #endif

要么

 /* Don't need this any more...
 #include "blah.h
 */
$ declare -a my_array
$ my_array=(`ls -1 *.cpp`)
$ echo ${my_array[0]}
a.cpp
$ echo ${my_array[1]}
b.cpp

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM