bash 如何替换 unix 文件中特定行的单词

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15646800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:00:02  来源:igfitidea点击:

How can I replace a word at a specific line in a file in unix

bashunixreplace

提问by user2012751

I've researched other questions on here, but haven't really found one that works for me. I'm trying to select a specific line from a file and replace a string on that line with another string. So I have a file named my_course. I'm trying to modify a line in my_course that starts with "123". on that line I want to replace the string "0," with "1,". Help?

我在这里研究了其他问题,但还没有真正找到适合我的问题。我正在尝试从文件中选择特定行并将该行上的字符串替换为另一个字符串。所以我有一个名为 my_course.txt 的文件。我正在尝试修改 my_course 中以“123”开头的一行。在这一行,我想用“1,”替换字符串“0,”。帮助?

回答by mikyra

One possibility would be to use sed:

一种可能性是使用sed

sed '/^123/ s/0/1/' my_course
  • In the first /../part you just have to specify the pattern you are looking for ^123for a line starting with 123.

  • In the s/from/to/part you have specify the substitution to be performed.

  • 在第一/../部分中,您只需要指定您要查找的^123以 123 开头的行的模式。

  • s/from/to/您已指定要执行的替换的部分中。

Note that by default after substitution the file will be written to stdout. You might want to:

请注意,默认情况下,替换后文件将写入标准输出。你可能想要:

  • redirect the output using ... > my_new_course

  • perform the substitution "in place" using the -eswitch to sed

  • 使用重定向输出 ... > my_new_course

  • 使用-e切换到 sed执行“就地”替换

If you are using the destructive in place variant you might want to use -iEXTENSIONin addition to keep a copy with the given EXTENSION of the original version in case something goes wrong.

如果您正在使用破坏性的就地变体-iEXTENSION,除了保留原始版本的给定 EXTENSION 的副本之外,您可能还想使用,以防出现问题。

EDIT:To match the desired lined with a prefix stored in a variable you have to enclose the sed script with double quotes "as using single qoutes 'will prevent variable expansion:

编辑:要将所需的内衬与存储在变量中的前缀相匹配,您必须用双引号将 sed 脚本括起来,"因为使用单 qoutes'将阻止变量扩展:

sed "/^$input/ s/0/1/" my_course

回答by Marcelo do Pagode

Have you tried this: sed -e '[line]s/old_string/new_string/' my_course

你试过这个: sed -e '[line]s/old_string/new_string/' my_course

PS: the [ ] shouldn't be used, is there just to make it clear that you should put the number right before the "s".

PS:不应该使用 [ ],只是为了明确表示您应该将数字放在“s”之前。

Cheers!

干杯!

In fact, the -e in this case is not necessary, I can write just

其实这种情况下的 -e 不是必须的,我可以直接写

sed '<line number>s/<old string>/<new string>/' my_course