Simple find and replace with sed

匿名 (未验证) 提交于 2019-12-03 00:59:01

问题:

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.

回答1:

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 


回答2:

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.



回答3:

to replace 1111 to 2222 you should probably try

cat textfile.txt | sed -e 's/1111/2222/g' 

or

cat textfile.txt | sed -e 's/1111/2222/g' > output.txt 

or

NUMBER=1111 ; NEWNUMBER=2222; cat textfile.txt | sed -e "s/$NUMBER/$NEWNUMBER/g" 

There's no need to create separate script for such trivial task. Note "-e" switch for sed, "g" appended at the end of quoted command, and the difference between single and double quotes.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!