10

我正在尝试替换文本文件中几个不同字符串中的数字。基本上它会采取以下形式

tableNameNUMBER
carNUMBER

我对 bash 和脚本很陌生,我不知道如何NUMBER用我传入的内容替换。所以我试过这个:

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

然后在命令行:

sh test.sh 123456

这只适用NUMBER于它本身,没有它tableName或在它car之前。NUMBER在这些情况下我该如何更换。是不是更好${NUMBER}?对不起,如果这些完全是菜鸟问题。

4

3 回答 3

10

这应该可以正常工作:

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

如果g它在一行上出现多次,则最后允许设置替换 NUMBER。

事实上,一个快速的测试:

foo.txt

carNUMBER
tableNameNUMBER
NUMBER
NUMBERfoo

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

这不是你的sed命令在做什么吗?

如果您想确保不会更改 NUMBER,除非它是单独的,请使用\baround NUMBER

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

如果您不关心 string 的大小写NUMBERi请在 sed 命令的末尾添加一个:

$ sed "s/NUMBER/$NUMBER/gi" foo.txt
于 2012-10-04T21:48:34.813 回答
3

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.

于 2012-10-05T01:13:43.317 回答
1

要将 1111 替换为 2222,您可能应该尝试

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

或者

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

或者

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

无需为此类琐碎的任务创建单独的脚本。注意 sed 的“-e”开关,在引用命令末尾附加的“g”,以及单引号和双引号之间的区别。

于 2012-10-04T21:12:08.503 回答