[英]How to loop a shell script across a specific file in all directories?
Shell Scripting sed Errors: Shell脚本sed错误:
Cannot view /home/xx/htdocs/*/modules/forms/int.php 无法查看/home/xx/htdocs/*/modules/forms/int.php
/bin/rm: cannot remove `/home/xx/htdocs/tmp.26758': No such file or directory / bin / rm:无法删除`/home/xx/htdocs/tmp.26758':无此类文件或目录
I am getting an error in my shell script. 我的shell脚本出现错误。 I am not sure if this for loop will work, it is intended to climb a large directory tree of PHP files and prepend a functions in every int.php file with a little validation.
我不确定此for循环是否能正常工作,它打算爬上PHP文件的大型目录树,并在每个int.php文件中添加一个函数,并进行一些验证。 Don't ask me why this wasn't centralized/OO but it wasn't.
不要问我为什么这不是集中式的/ OO,但不是。 I copied the script as best I could from here: http://www.cyberciti.biz/faq/unix-linux-replace-string-words-in-many-files/
我尽可能从此处复制脚本: http : //www.cyberciti.biz/faq/unix-linux-replace-string-words-in-many-files/
#!/bin/bash
OLD="public function displayFunction(\$int)\n{"
NEW="public function displayFunction(\$int)\n{if(empty(\$int) || !is_numeric(\$int)){return '<p>Invalid ID.</p>';}"
DPATH="/home/xx/htdocs/*/modules/forms/int.php"
BPATH="/home/xx/htdocs/BAK/"
TFILE="/home/xx/htdocs/tmp.$$"
[ ! -d $BPATH ] && mkdir -p $BPATH || :
for f in $DPATH
do
if [ -f $f -a -r $f ]; then
/bin/cp -f $f $BPATH
sed "s/$OLD/$NEW/g" "$f" > $TFILE && mv $TFILE "$f"
else
echo "Error: Cannot view ${f}"
fi
done
/bin/rm $TFILE
Do wildcards like this even work? 这样的通配符还能用吗? Can I check in every subdirectory across a tree like this?
我可以像这样在树上签入每个子目录吗? Do I need to precode an array and loop over that?
我是否需要对数组进行预编码并对其进行循环? How would I go about doing this?
我将如何去做呢?
Also is, the $ in the PHP code breaking the script at all? 同样,PHP代码中的$根本破坏了脚本吗?
I am terribly confused. 我非常困惑。
/
in OLD which is used in a s///
sed command. s///
sed命令中使用的OLD中使用/
。 This won't work [ ! -d $BPATH ] && mkdir -p $BPATH || :
[ ! -d $BPATH ] && mkdir -p $BPATH || :
is horrible. [ ! -d $BPATH ] && mkdir -p $BPATH || :
太可怕了。 use mkdir -p "$bpath" 2>/dev/null
mkdir -p "$bpath" 2>/dev/null
Assuming you are using GNU sed, I'm not used to other sed flavors. 假设您使用的是GNU sed,我不习惯其他sed风格。 If you are not using GNU sed, replacing the
\\n
with a newline (inside the string) should work. 如果您不使用GNU sed,则应该用换行符(在字符串内)替换
\\n
。
#!/usr/bin/env bash
old='public function displayFunction(\$int)\n{'
old=${old//,/\\,} # escaping eventual commas
# the \$ is for escaping the sed-special meaning of $ in the search field
new='public function displayFunction($int)\n{if(empty($int) || !is_numeric($int)){return "<p>Invalid ID.</p>";}\n'
new=${new//,/\\,} # escaping eventual commas
dpath='/home/xx/htdocs/*/modules/forms/int.php'
for f in $dpath; do
[ -r "$f" ]; then
sed -i.bak ':a;N;$!ba;'"s,$old,$new,g" "$f"
else
echo "Error: Cannot view $f" >&2
fi
done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.