custom search and replace (csed)

Posted by Lance Ivy Wed, 04 Jul 2007 12:29:00 GMT

So you’re working on a large codebase and need to change something. But it’s all over the place. Why hunt it down when you can do an easy search-and-replace right from the shell? I wrote this shell script back in my PHP days when I had to move some database tables around. It’s not the prettiest (it is written in bash), but it’s functional and gets the job done.

To install, place this script in your $PATH (I like to put stuff like this in ~/bin/) and you’re good to go. The csed script operates recursively from your current directory.

Script is available after the jump.

Note: there’s a bug I haven’t bothered to fix related to the result set size. It’s really benign, don’t worry.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
#!/bin/bash

###
# The prompt that starts things off
###
function start
{
  echo
  echo -e 33[1mSearch and Replace33[0m
  echo
}

###
# Quitting with style
###
function quit
{
  echo
  echo ----------------------------------------
  echo
  exit
}

###
# Takes a collection of strings and prompts the user to pick one.
# Assumes that the leading character of each option is unique, and
# lets the user pick an option by that character.
# The option list is horizontal.
# Does case insensitive matching.
#
# The response is in the global $REPLY variable, and is lowercase.
###
function ask_horizontal
{
  # prompt for the first character of some option
  echo -n 'Choose: '
  for option in $@; do
    option=`echo -n $option | sed s/^./\\\33[1m\\\\33[0m/`
    echo -e -n $option
    echo -n '  '
  done
  echo -n "? "
  read -n1 answer
  echo ''

  # now lookup the original option (full string) and return that
  REPLY=''
  for option in $@; do
    if [[ `echo -n "$option" | grep -Ei "^$answer"` ]]; then
      REPLY=$option
    fi
  done
}

###
# the help text
###
function print_help
{
  cat <<-EOL
        ----------------------------------------------------
        csed: a sed-based recursive search and replace

        syntax: csed (options) <find> <replace>

        options:
          -h       this help message
          -g       use piped-in grep. grep must be formatted
                   with -EHinr

        <find>     an extended regular expression
        <replace>  a string with sed-style backreferences

        ----------------------------------------------------
    EOL
  exit
}

start

###
# Collect script options
###
results=''
while getopts ":hg" flag; do
  case $flag in
    h ) print_help;;
    g )
      # buffer the results list from stdin
      while read line; do
        if [ -z "$line" ]; then continue; fi
        if [ -z "results" ]; then
          results=$line;
        else
          results="$results
$line"
        fi
      done

      # return stdin to the terminal (keyboard)
      exec 0</dev/tty
      ;;
  esac
done
shift $(($OPTIND - 1))

if [ $# -lt 2 ]; then print_help; fi

find=${1////\/}    # escape slashes for the sed expression
replace=${2////\/}    # ditto

if [ -z "$results" ]
then
  # first convert some sed pecularities to grep syntax
  grep_find=${find//\\(/(}
  grep_find=${grep_find//\\)/)}
  results=`grep -EHinr "$grep_find" ./ --color=never`
fi

# set IFS (internal field separator) to newline, so our 'for' loop reads lines
IFS="
"
result_count=`echo -n "$results" | wc -l`
result_counter=0
for line in $results
do
  # we want to parse the following syntax: "^[filename]:[line number]: [line]$"
  file=${line%%:*}      # strip from first : to end
  line=${line#*:}       # strip from beginning to first : (the file part)
  line_num=${line%%:*}    # strip from first : to end
  code=${line#*:}    # strip from beginning to first :

  new_code=`echo $code | sed "s/$find/$replace/g"`
  result_counter=$(($result_counter + 1))

  ######################
  # feedback / preview #
  ######################
  echo -e "[$result_counter/$result_count] ${file}, line ${line_num}"
  echo -n "- "
  echo -e `echo $code | sed -e "s/$find/\\33[1;34m&\\33[0m/g"`
  echo -n "+ "
  echo -e `echo $code | sed -e "s/$find/\\33[1;34m${replace}\\33[0m/g"`

  ######################
  # ask for what to do #
  ######################
  if [[ $replace_all == 'yes' ]]
  then
    action='Replace'
  else
    ask_horizontal 'Replace' 'All' 'Skip' 'Custom' 'Quit'
    action=$REPLY
    echo ''
  fi

  ##############################
  # act according to direction #
  ##############################
  if [[ $action == 'All' ]]
  then
    replace_all=yes
    action='Replace'
  fi

  case "$action" in
    "Custom" )
      echo -n 'enter a custom replace string: '
      read replace2
      sed -e "${line_num}s/$find/$replace2/g" "$file" > /tmp/csed$$ 
        && cat /tmp/csed$$ > $file && rm /tmp/csed$$
      ;;

    "Replace" )
      sed -e "${line_num}s/$find/$replace/g" "$file" > /tmp/csed$$ 
        && cat /tmp/csed$$ > $file && rm /tmp/csed$$
      ;;

    "Quit" )
      quit
      ;;

    "Skip" )
      continue
      ;;

    * )
      ### TODO: reprompt user! well, ok, right now it's just a skip
      continue
      ;;
  esac
done

quit

Posted in  | Tags ,  | no comments

Comments

(leave url/email »)

   Comment Markup Help Preview comment