Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 为什么我的命令失败了?_Bash_Sed_Find - Fatal编程技术网

Bash 为什么我的命令失败了?

Bash 为什么我的命令失败了?,bash,sed,find,Bash,Sed,Find,因此,我的命令应该搜索所有的.htaccess文件,并对其中包含“RedirectMatch”的文件进行grep处理,一旦完成,应该通过管道将其发送到sed以注释掉这行 运行 for i in `find `pwd` -name .htaccess -exec grep -q "RedirectMatch" {} \; -print`; do $i | sed -i 's/RedirectMatch/#RedirectMatch/g'; done 实际上,它给了我一个包含“RedirectMa

因此,我的命令应该搜索所有的.htaccess文件,并对其中包含“RedirectMatch”的文件进行grep处理,一旦完成,应该通过管道将其发送到sed以注释掉这行

运行

for i in `find `pwd` -name .htaccess -exec grep -q "RedirectMatch" {} \; -print`; do $i | sed -i 's/RedirectMatch/#RedirectMatch/g'; done
实际上,它给了我一个包含“RedirectMatch”的.htaccess文件列表,但当我在循环中运行它时,它会抛出一个巨大的文件列表,即使是未命名为.htaccess的文件


有什么想法吗?感谢所有帮助。

这是因为您的回执:您的命令实际执行了
find
,然后将
pwd
字符串附加到它,然后尝试执行其余的

使用
$(…)

由于默认情况下
find
在默认情况下会在当前目录中查找,如果没有指定,则可以进一步指定:

for i in $(find $(pwd) -name .htaccess -exec grep -q "RedirectMatch" {} \; -print); do sed -i 's/RedirectMatch/#RedirectMatch/g' $i; done

(编辑:还修复了sed命令的调用)

该命令有一些问题:

首先,您需要转义嵌套的反勾号,以便它们按照您认为的方式工作:

for i in $(find -name .htaccess -exec grep -q "RedirectMatch" {} \; -print); do sed -i 's/RedirectMatch/#RedirectMatch/g' $i; done
或者使用首选的子shell表示法:

`find \`pwd\` -name .htaccess -exec grep -q "RedirectMatch" {} \; -print`
其次,在使用就地
-i
标志时,不能通过管道进入
sed
。我不确定您试图在这里实现什么,但我认为您应该在每个文件上运行
sed
,如果字符串不在那里,则不会替换任何内容,并且不会降低效率。您所做的操作不会以任何方式编辑任何文件,您只是在stdin中的文件名上运行
sed
,而不是文件本身!比如说:

$(find $(pwd) -name .htaccess -exec grep -q "RedirectMatch" {} \; -print)

注意:
-i
后面的引号对于我的
sed
(在darwin上运行)是必需的,它们满足了
-i
标志对参数的需要,对于大多数
sed
可能不需要。还有人提到,调用
pwd
是不必要的,所以我用

来交换,这里给出的答案是危险的错误——它们可以被操纵来包含任意输出(想想有人创建一个名为
“//etc/passwd/.htaccess”的文件)
,从而导致脚本编辑
/etc/passwd


或者更好的方法是,用
find.
交换
find$(pwd)
并保存一个进程。在这种情况下,最好完全删除目录参数;)默认情况下,
find
在当前目录中查找;你是说
。。。执行sed的/RedirectMatch/#RedirectMatch/“$i”;完成
,其中替换可以进一步缩写为#&。是的,我已经修复了它。(在其参数中,
-i
直接替换)。GNU find默认为当前目录,但其他一些实现不允许省略该目录。
$(find $(pwd) -name .htaccess -exec grep -q "RedirectMatch" {} \; -print)
find . -name .htaccess -exec sed -i "" 's/RedirectMatch/#RedirectMatch/g' {} \;
while IFS='' read -r -d '' filename; do
  sed -i -e 's/^([^#]+)RedirectMatch/\1#RedirectMatch/' "$filename"
done < <(find . -name .htaccess -print0)
while IFS='' read -r -d '' filename; do
  ex "$filename" -s - <<<'%s/^\([^#]*\)RedirectMatch/\1#RedirectMatch/'$'\n''x'
done < <(find . -name .htaccess -print0)