bash - How to prompt to the user while performing a find>replace in unix -


i'm trying write script works microsoft words find>replace function. first asks 2 inputs user. first 1 strings found , second 1 strings replace old ones. though pretty straight forward, want count number of things replaced , echo user confirms these specific number of replacements. how can that? far have search>replace function:

for file in `find -name '*.sdf.new'`;         grep "$search" $file &> /dev/null       sed -i "s/$search/$replace/" $file   done 

while read -u 3 -r -d '' file;     n=$(grep -o "$search" "$file" | wc -l)     read -p "about replace $n instances of '$search' in $file. ok? " ans     if [[ $ans == [yy]* ]];         sed -i "s|${search//|/\\\\|}|${replace//|/\\\\|}|g" "$file"     fi done 3< <(find -name '*.sdf.new' -print0) 

there's tricky stuff going on here:

  • the output find command send while loop on file descriptor 3, , read uses fd grab filenames
    • this necessary because there read command inside loop interact user has use stdin.
  • the while loop reads process substitution <(find -name ...) no subshell has created , facilitate use of different file descriptor.
    • in bash, when cmd1 | cmd2, new bash processes created each side of pipe. can cause problems in variables assigned in subshell not present in current shell, not case here.
  • to handle files weird names, use gnu find -print0 feature separates filenames 0 byte, , use read's -d '' option.
  • grep -c counts number of lines match. grep -o pattern file | wc -l counts number of actual matches.
  • the crazy sed script adds protection in case search or replacement strings contain s commands delimiter. use | instead of / because escaping got more extreme.

Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -