Have you ever found yourself googling how to find and replace within a file from the linux command line? Me too. Here’s the answer that works for me: sed -i 's/search/replace/g' /path/to/file.txt
Rather than type that command all the time, I wrote a bash script to simplify things. BE WARNED! I know very little about bash scripting or the sed command, so this script probably only works for simple search and replace strings. I bet it would break if either string contained quotes or other reserved characters. That being said, it works like a charm for simple stuff. I named it esed (for easy sed).
Usage: esed search replace /path/to/file.txt
It’ll ask you to confirm the replace, then after a successful run it’ll show the contents of the file. I’ve found that useful for small files, but not so useful for big ones. You could always comment that line out if it annoys you. :)
[note color=”#DDD”]Download
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 |
#! /bin/bash # mysearch=$1 myrep=$2 myfile=$3 if [ $# -eq 3 ] then read -p "*** Are you sure you want to replace \"$mysearch\" with \"$myrep\" in \"$myfile\"? *** " -n 1 -r if [[ $REPLY =~ ^[Yy]$ ]] then echo "" # Find and replace sed -i 's/'$mysearch'/'$myrep'/g' $myfile echo "*** Done! ***" echo "*** cat $myfile ***" cat $myfile else echo "" echo "*** Operation Cancelled ***" fi else echo "*** Missing Parameters! (esed search replace file) ***" fi exit |