Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple find and replace with sed

Tags:

bash

I'm trying to replace a number that is in a couple different strings in a text file. Basically it would take the form of

tableNameNUMBER
carNUMBER

I'm pretty new to bash and scripting and I wasn't sure how to replace NUMBER with what I pass in. So I've tried this:

#! /usr/bin/env bash
sed "s/NUMBER/$1/" myScript.txt > test.txt

then at the command line:

sh test.sh 123456

This only works if NUMBER is on its own, without tableName or car preceding it. How can I replace NUMBER in those cases. Is it better to have ${NUMBER}? Sorry if these are totally noob questions.

like image 590
Crystal Avatar asked Oct 04 '12 20:10

Crystal


2 Answers

This should work just fine:

sed "s/NUMBER/$1/g" myScript.txt > test.txt

The g on the end allows set to replace NUMBER if it appears multiple times on one line.

In fact, a quick test:

foo.txt

carNUMBER
tableNameNUMBER
NUMBER
NUMBERfoo

$ NUMBER=3.14
$ sed "s/NUMBER/$NUMBER/g" foo.txt
car3.14
tableNumber3.14
3.14
3.14foo

Isn't that what your sed command is doing?

If you want to make sure you don't change NUMBER unless it's by itself, use \b around NUMBER:

$ sed "s/\bNUMBER\b/$NUMBER/g" foo.txt
carNumber
tabelNumberNUMBER
3.14
NUMBERfoo

If you don't care about the case of the string NUMBER, put an i on the end of the sed command:

$ sed "s/NUMBER/$NUMBER/gi" foo.txt
like image 84
David W. Avatar answered Nov 15 '22 20:11

David W.


Since you've stated you're new to this, I'm going to first answer some problems that you haven't asked.

Your shebang is wrong

The first bytes of your script should be #! (a hash and an exclamation mark; referred to as a shebang). You have #1 (hash-one), which is gibberish. This shebang line tells the system to use bash to interpret your file (i.e. your script) when executed. (More or less. Technically speaking, it's actually given to env, which finds bash before handing it over.)

Once you've fixed up the shebang, set the permissions on the script to let the system know it's executable:

$ chmod a+x test.sh

Then run it like so:

$ ./test.sh 123456

As @gokcehan also commented, running your script with sh ... when you have a shebang is redundant, and isn't preferable for other reasons.


As for what you were asking, you can easily test your regex replacement:

$ echo tableNameNUMBER | sed "s/NUMBER/123456/"
tableName123456

And it seems to work just fine.

Note: The preceding $ merely denotes that I typed it into my console and isn't part of the actual command.

like image 36
antak Avatar answered Nov 15 '22 20:11

antak