使用 SED、AWK 或 GREP 检查多个文件中第一个字符的出现



假设我有这样的文件:

      a  void measure()    
         {
      a  GPIOPinTypeADC(GPIO_PORTE_BASE, GPIO_PIN_7); // Pin assignment
         ADCSequenceConfigure(ADC0_BASE, 3, ADC_TRIGGER_PROCESSOR, 0);
         appended line for demonstration
         ADCSequenceStepConfigure(ADC0_BASE, 3, 0, ADC_CTL_CH0 | ADC_CTL_IE |ADC_CTL_END);
         ADCSequenceEnable(ADC0_BASE, 3);//sample sequence 3 is enabled.
         ADCIntClear(ADC0_BASE, 3);   // Clear the interrupt status flag.
         }

我是否可以使用 SEDAWK 输出 true,当且仅当a附加到第一个以空格为分隔符的列前。第一个字符总是a否则是空格。

截至目前,我使用GREP

    if grep -q "^a" file.c; then
       echo "The file is prepended"
       else
       echo "the file is clean"
   fi

我在单独的文件中有几个像上面第一个这样的函数,并希望根据前面的a对其进行分类。

是否可以使用GREP本身轻松地在多个文件上执行此操作。我真的更喜欢SEDAWK的替代方案,避免使用数百人的if结构。

建议或更好的算法总是受欢迎的:)

很难

说出你在问什么,但听起来你可能想要这个

grep -q ^a file.c && echo 'The file is appended' || echo 'the file is clean'

或者也许你真的想要这个:

grep -L ^a *.c

每个生成的文件名都是一个"附加"文件。

对于多个文件,您可以这样做

for file in *.c ; do
   grep -q '^a ' file.c && echo 'The file is appended' || echo 'the file is clean'
done

对于递归方式的多个文件,请尝试

find . -type f -name '*.c' -exec grep -q '^a ' {} ; -print

尽管要获得"正确"的输出,您需要做更多的工作。

你为什么要用cat
您可以使用 grepsedawk 指定任意数量的文件,但我不清楚您是否希望每个文件都为 'True',如果任何文件包含此模式,则为 tru。 让我们假设前者:

awk '/^a /{print FILENAME "is True"}' 'list-of-files'

尝试以下命令:

awk 'FNR==1&&($1=="a") {printf "The file %s is prependedn",FILENAME}' *.c

相关内容

最新更新