Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
831 views
in Technique[技术] by (71.8m points)

bash - Simple find and replace with sed

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 around NUMBER:

$ sed "s/NUMBER/$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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...