[英]How to insert a new line of code in only perl scripts with Bash script
I have a Linux folder tree with mixed shell, Perl and Python scripts. 我有一个混合了shell,Perl和Python脚本的Linux文件夹树。 None of the scripts have consistent file extensions (.pl, .perl, .py, .sh, or no extension at all). 这些脚本都没有一致的文件扩展名(.pl,.perl,.py,.sh或根本没有扩展名)。 I need to identify which files are Perl scripts, then add a new line of code to set a variable if the variable is not already in the Perl script. 我需要确定哪些文件是Perl脚本,然后如果该变量不在Perl脚本中,则添加一行新代码来设置一个变量。
Thanks to How to insert newline character after comma in `),(` with sed? I came up with this code that uses sed to insert the new line of code. 感谢如何在'),(`中用sed插入逗号后的换行符?我想到了使用sed插入新行代码的代码。
This code works, but is there a more efficient way to do it? 这段代码有效,但是有更有效的方法吗?
#! /bin/bash
NL='
$|++'
for f in `find "$1" -type f`
do
if [ $(grep -cP "^\#\!/.+/perl" "${f}") -gt 0 ]
then
if [ $(grep -c "$|" "${f}") -eq 0 ]
then
sed -i -r "s/^#!\/(.+)\/perl(.+)$/#!\/\1\/perl\2\\${NL}/g" "${f}"
fi
fi
done
You have a number of Useless Uses of Grep -c there. 那里有许多Grep -c的无用用法。 See http://porkmail.org/era/unix/award.html 参见http://porkmail.org/era/unix/award.html
#! /bin/bash
NL='
$|++'
for f in `find "$1" -type f`
do
grep -qP "^\#\!/.+/perl" "${f}" &&
! grep -q "$|" "${f}" &&
sed -i -r "s/^#!\/(.+)\/perl(.+)$/#!\/\1\/perl\2\\${NL}/g" "${f}"
done
The short-circuit &&
is not an optimization, just a personal preference. 短路&&
并非优化,只是个人喜好。 You could just as well keep your nested if
s, or perhaps something like 你也可以嵌套嵌套if
或类似的东西
if grep -qP "^#!/.+/perl" "$f" && ! grep -q "$|" "$f"; then ...
It might be more efficient still to do the first grep (at least) in a sed
script since presumably you are only interested in the first line of the script. 仍然(至少)在sed
脚本中进行第一个grep可能仍然更有效率,因为大概您只对脚本的第一行感兴趣。 (On the other hand, why do you have a /g
flag on the sed
substitution if that is the case?) (另一方面,如果是这种情况,为什么在sed
替换项上有一个/g
标志?)
Actually you probably mean 其实你可能是说
sed -i -r "1s%^(#!/.+/perl.*)$%\1\\${NL}%" "$f"
You could also use the file(1)
command: 您也可以使用file(1)
命令:
$ head -n 1 perl_script_wo_ext
#!/usr/bin/perl
$ file perl_script_wo_ext
perl_script_wo_ext: Perl script, ASCII text executable
Then grep for \\bPerl script\\b
in that and you're set. 然后在其中使用\\bPerl script\\b
grep进行设置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.