简单的查找和替换SED [英] Simple find and replace with sed

查看:103
本文介绍了简单的查找和替换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

我是pretty新的抨击和脚本,我不知道如何更换 NUMBER 与我通。所以我已经试过这

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:

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

然后在CMD行:

then at the cmd line:

sh test.sh 123456

这仅适用于如果 NUMBER 是自己的,不用 tableName值 preceding它。我怎么能代替 NUMBER 在这种情况下。它是最好能有 $ {NUMBER} ?很抱歉,如果这是完全小白的问题。

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.

推荐答案

这应该只是罚款:

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

先按g 对端允许设置,如果多次出现在一行中更换号码。

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

事实上,一个快速测试:

In fact, a quick test:

carNUMBER
tableNameNUMBER
NUMBER
NUMBERfoo

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

这不就是你的 SED 命令是干什么的?

如果你想确保你的不要更改号码,除非它本身,使用 \\ b 围绕 NUMBER

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

如果你不关心字符串的情况下, NUMBER ,把一个 I 上月底sed命令:

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

这篇关于简单的查找和替换SED的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆