Bash 如何在执行查找时提示用户>;在unix中替换
我正在尝试编写一个脚本,它的工作原理基本上类似于MicrosoftWordsFind>replace函数。 它首先要求用户提供两个输入。第一个用于查找字符串,第二个用于替换旧字符串。尽管这很简单,但我还想计算要替换的东西的数量,并回应用户确认这些具体的替换数量。我该怎么做?到目前为止,我将其作为搜索>替换功能:Bash 如何在执行查找时提示用户>;在unix中替换,bash,shell,unix,exit,status,Bash,Shell,Unix,Exit,Status,我正在尝试编写一个脚本,它的工作原理基本上类似于MicrosoftWordsFind>replace函数。 它首先要求用户提供两个输入。第一个用于查找字符串,第二个用于替换旧字符串。尽管这很简单,但我还想计算要替换的东西的数量,并回应用户确认这些具体的替换数量。我该怎么做?到目前为止,我将其作为搜索>替换功能: for file in `find -name '*.sdf.new'`; do grep "$search" $file &> /dev/null
for file in `find -name '*.sdf.new'`;
do
grep "$search" $file &> /dev/null
sed -i "s/$search/$replace/" $file
done
读取-u3-r-d“”文件时;做
n=$(grep-o“$search”“$file”| wc-l)
read-p“即将替换$file.OK中“$search”的$n个实例?”回答
如果[[$ans==[yY]*];然后
sed-i“s |${search//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\}g”“$file”
fi
完成3<如果您使用grep只是为了检查文件中是否存在模式,请执行以下操作:如果grep-q“$search”“$file”;然后
——它将在第一次匹配后立即返回success,而不必扫描整个文件,因此效率更高。另外,您不必存储任何输出。
check_val=`grep "$search" $file`
if [[ "x$check_val" != "x" ]]
then
read -p "replace ?" response;
if [[ "$response" == "y" ]]
then
sed -i "s/$search/$replace/" $file
fi
fi
while read -u 3 -r -d '' file; do
n=$(grep -o "$search" "$file" | wc -l)
read -p "About to replace $n instances of '$search' in $file. OK? " ans
if [[ $ans == [yY]* ]]; then
sed -i "s|${search//|/\\\\|}|${replace//|/\\\\|}|g" "$file"
fi
done 3< <(find -name '*.sdf.new' -print0)