我有很大的 .c 和 .h 文件,我必须从中只选择满足以下这些条件的预处理器指令
#if(VALUE==5) ||(VALUE==6)
预处理器指令的其余部分应该保持不变。我已经研究过 unifdef
和 sunifdef
它们将允许我识别 #if
和 #ifdef
但我不想选择所有 #if
、#ifdefs
。是否有一个实用程序允许我给出,例如 VALUE==5
并只选择那些?
基本上我需要根据我的输入值选择预处理器指令。
最佳答案
尝试运行脚本,它将打印代码行和#if block 中的代码。 这只会静态扫描文件。你可以试一试。
# ./run.sh filename "String to search in if"
# example ./run.sh test.h "#if VALUE"
# Get the line number of Searching string locations
# store it in a file
awk "/$2/{ print NR }" $1 > temp_if
# to store total lines present inside the if contruct
totalLinesCount=0
# read one line at a time, that is go through one occurance of string at a time
while read matchLineNum
do
printf "Match Found in line number $matchLineNum\n"
#search for first occurance of #elif from the matched string.
elifLineNum=$(tail -n +$(expr $matchLineNum + 1) $1 | awk "/#elif/{ print NR;exit }")
if [ "$elifLineNum" == "" ]
then
# if not found set it to some high value
elifLineNum=$(wc -c $1)
fi
elseLineNum=$(tail -n +$(expr $matchLineNum + 1) $1 | awk "/#else/{ print NR;exit }")
if [ "$elseLineNum" == "" ]
then
elseLineNum=$(wc -c $1)
fi
endifLineNum=$(tail -n +$(expr $matchLineNum + 1) $1 | awk "/#endif/{ print NR;exit }")
# check if #endif / #elif / #else occurs first
if [ $endifLineNum -lt $elseLineNum -a $endifLineNum -lt $elifLineNum ]
then
# store the code count
totalLinesCount=$(expr $totalLinesCount + $(expr $endifLineNum - 1))
# store the code
tail -n +$(expr $matchLineNum + 1) $1 | head -n $(expr $endifLineNum - 1) >> out
elif [ $elseLineNum -lt $endifLineNum -a $elseLineNum -lt $elifLineNum ]
then
totalLinesCount=$(expr $totalLinesCount + $(expr $elseLineNum - 1))
tail -n +$(expr $matchLineNum + 1) $1 | head -n $(expr $elseLineNum - 1) >> out
elif [ $elifLineNum -lt $elseLineNum -a $elifLineNum -lt $endifLineNum ]
then
totalLinesCount=$(expr $totalLinesCount + $(expr $elifLineNum - 1))
tail -n +$(expr $matchLineNum + 1) $1 | head -n $(expr $elifLineNum - 1) >> out
else
printf "\n Error \n"
fi
done < temp_if
printf "\nTotal number of lines present inside the given condition is $totalLinesCount\n"
rm -f temp_if
printf '\nFinal Extracted Out\n'
cat out
rm -f out
关于c - c中#ifdefs的选择性预处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28323539/