-1

I'm new in Unix, and I'm learning about sed command. I need to write a very small script for searching a number in a file and replacing it. I tried doing grep, and than deleting the specific phone number from a file, and then adding another one. But i was told that i can use sed in a script to replace. I know how to use the sed command on a command line for search, and replacing something. But how do i write a script, which lets the user search a number, and then let the user enter the number which they want to replace the old number with.

So far what i did was use grep to find a number, that works. but now I'm stuck at how can i let the user add in the new number, so the new number can replace the old one. I tried piping grep to sed, and vice versa. No luck so far. I sound redundant, :/ but I'm really frustrated. Any help will be appreciated :D.

1 Answers1

2

Here's a starting point for you:

#!/bin/bash

PHONEFILE=/path/to/your/file

# Prompt for search and replace numbers
# and simply exit if either is empty
# (in your actual script, you'll need to flesh this out with
# proper validation of phone number formats, error messages etc.!)
read -p "Number to search for: " oldnum
if [ ! "$oldnum" ]; then exit; fi

read -p "Replace with number: " newnum
if [ ! "$newnum" ]; then exit; fi

# Search and replace, change the phone file directly
# and create a backup of the previous version with .bak extension
# This assumes a file containing one phone number per line
sed -i .bak 's/^'"$oldnum"'$/'"$newnum"'/' $PHONEFILE
Guido
  • 4,114
  • It also assumes BSD sed, and assumes that you won't change the value of PHONEFILE to something with special characters in it (since you didn't quote it in the final line). – Wildcard Apr 06 '16 at 06:29
  • 1
    I'm not sure why you use Bash above, rather than something less heavyweight, but since you do, is there a good reason to prefer echo; read over read -p? Just wondering. – Toby Speight Apr 06 '16 at 08:18
  • @TobySpeight Since the OP stated that she's new in Unix and I don't know where she wants to go from here with her script, I would recommend bash to her for the built-in convenience, just in case. Also, this did not seem to me like a time or memory-critical application which would demand the use of a lightweight shell per se (the weight-lifting is done by sed alone, not by the surrounding script… at this stage). – Guido Apr 06 '16 at 11:37
  • @TobySpeight And you're right about the read -p. I updated this, thanks. Bad PHP habits… – Guido Apr 06 '16 at 11:38
  • 1
    That seems a good reason to use Bash - I just wanted to point out (for didactic purposes) that one can/should choose which shell to use for each script. – Toby Speight Apr 06 '16 at 11:56
  • Thank you, I just didn't knew how to start it. This should really help. – Sophia_T213 Apr 07 '16 at 02:42