Using Bash/Perl to modify files based on each file's name

冷暖自知 提交于 2020-01-04 03:57:15

问题


I have a few hundred files which all contain variations of the same class, 'Process'. My intention is to make each class a derived class of some base clase 'BaseProcess'. Every file has been manually renames to something like 'Process_XXX' and I am trying to find a way of going through every file and changing every occurrence of, for example:

class Process {
    stuff;
}

to

class Process_XXX : public BaseProcess {
    stuff;
}

where XXX is taken from the particular file being changed. Is this possible using Bash or Perl scripting? Or is it best to proceed manually? Cheers Jack


回答1:


I'll add an answer taking into account the file extensions (adding the changes I suggested to the answer by fedorqui) as well as improvements from DVK's answer:

for SUFFIX in cc h java txt; do
    for file in *.$ext; do
        sed -i.bak "s#^\\(\\s*class\\s\\+Process\\)\\(\\s*{\\)#\\1_${file/%.$SUFFIX} : public BaseProcess\2#g" $file
    done
done

An example of the pattern is s#^\(\s*class\s\+Process\)\(\s*{\)#\1_AlertGenerator : public BaseProcess\2#g with the XXX being AlertGenerator . I'm using the two \(...\) to extract the matches and use them in the replacement pattern as \1 and \2 (called back references in info sed).




回答2:


If files are in the same dir and have a same pattern name like file, this can make it:

for file in file*
do
   sed -i.bk "s/Process/Process_$file : public BaseProcess/g" $file
done

Note that with -i.bk a backup file $file.bk will be created.

Tested successfully with three files: file1, file2, file3.




回答3:


perl -pi.bak -e \
   's#^\s*class Process {#class Process : public BaseProcess_$ARGV {#g;' \
   Process_XXX
mv *.bak /your/backup/directory

This is similar to SED's solution (part of Perl's roots are in sed :) but the benefit is that it can be easily extended if more complicated tasks are needed. E.g. if your files are in various sub-directories, you can use Perl's File::Find; or you can rename the files if needed.



来源:https://stackoverflow.com/questions/17788236/using-bash-perl-to-modify-files-based-on-each-files-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!