Linux Shell脚本去掉几类常见文件中的注释推荐

Linux操作系统中去掉各类文件中的注释这个功能比较常用,通常用在查看一个较长的文件,又不想看注释的情况。通常这些文件包括C语言编写的*.c、*.h文件、cpp文件、*.xml文件、*.sh shell脚本文件、*.ini *.conf配置文件、*.php *.py *.pl等编程语言编写的文件以及无扩展名的一些可执行文件等。

实现这个功能并不复杂,通常注释风格就那么几种,在编写脚本过程中只需要编写出合适的正则表达式以及运用适当的文本处理工具(grep、sed等)即可。

针对几种常见的注释风格编写一个脚本文件代替cat更会省力一些。

脚本如下:

此脚本可以从GitHub上获取,欢迎issue、fork、star:https://github.com/DingGuodong/LinuxBashShellScriptForOps/blob/master/functions/string/noComment2.sh

#!/bin/bash#deleteallspacesandcommentsofspecializedfile,usingwith$@filenameDEBUG=falseif${DEBUG};thenold_PS4=$PS4#systembuiltinvariabledoesnotneed'${var}'expression#exportPS4='+${BASH_SOURCE}:${LINENO}:${FUNCNAME[0]}:'exportPS4='+${LINENO}:${FUNCNAME[0]}:'#ifthereisonlyonebashscript,donotdisplay${BASH_SOURCE}_XTRACE_FUNCTIONS=$(set+o|grepxtrace)set-oxtracefunctionis_file_exist(){test-f$1||echo"ls:cannotaccess$file:Nosuchfileordirectory" exit1functiondos2unix_text_file_format_converter(){ifcat-A${file}|grep'\^M\\$' /dev/null||file${file}|grep"withCRLFlineterminators" /dev/null;thenwhichdos2unix /dev/null2 1||yum-q-yinstalldos2unix||apt-get-qq-yinstalldos2unixdos2unix${file} /dev/nullfifunctiondel_comment_in_c_cpp_file(){tmp_file=/tmp/.noComment_$(date+%Y%m%d%H%M%S%N$RANDOM)cp${file}${tmp_file}#deletethecommentlinebeginwith'//comment'sed-i"/^[\t]*\/\//d"${tmp_file}#deletethecommentlineendwith'//comment'sed-i"s/\/\/[^\"]*//"${tmp_file}#deletethecommentonlyoccupiedoneline'/*comment*/'sed-i"s/\/\*.*\*\///"${tmp_file}#deletethecommentthatoccupiedmanylines'/*comment#*comment#*/sed-i"/^[\t]*\/\*/,/.*\*\//d"${tmp_file}grep-v^$${tmp_file}\rm-f${tmp_file}functiondel_comment_in_sh_conf_file(){#ignorethecommentlineendwith'#comment'grep-v"^[\t]*\#"${file}|grep-v"^$"functiondel_comment_in_xml_file(){iftest-f${file} file${file}|grep"XML" /dev/null;thenwhichtidy /dev/null2 1||yum-q-yinstalltidy /dev/null2 1||apt-get-qq-yinstalltidy /dev/null2 1tidy-quiet-asxml-xml-indent-wrap1024--hide-comments1${file}elsewhichtidy /dev/null2 1||yum-q-yinstalltidy /dev/null2 1||apt-get-qq-yinstalltidy /dev/null2 1tidy-quiet-asxml-xml-indent-wrap1024--hide-comments1${file}fifunctiondel_comment_in_general_file(){#ignorethecommentlineendwith'#comment'grep-v"^[\t]*\#"${file}|grep-v"^[\t]*\;"|grep-v"^$"你被雨淋湿的心,是否依旧。

Linux Shell脚本去掉几类常见文件中的注释推荐

相关文章:

你感兴趣的文章:

标签云: