bash 如何在bash中的文件中特定行的末尾附加字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22159044/
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-10 00:42:46  来源:igfitidea点击:

How to append a string at end of a specific line in a file in bash

bashsedawk

提问by Chris F

I want to append an alias to the end of a certain line of my hosts file. For example

我想在我的主机文件的某一行的末尾附加一个别名。例如

I have

我有

192.168.1.1    www.address1.com
192.168.1.2    www.address2.com
192.168.1.3    www.address3.com

I want to it to look like

我想让它看起来像

192.168.1.1    www.address1.com
192.168.1.2    www.address2.com myalias
192.168.1.3    www.address3.com

I want to find the line that contains 19.2.68.1.2 and append myalias at the end of it. The line is not necessarily the second line in the file like I've shown here. It could be anywhere.

我想找到包含 19.2.68.1.2 的行并在其末尾附加 myalias。该行不一定是文件中的第二行,就像我在此处显示的那样。它可以在任何地方。

回答by Steve

Using sedand the pattern described:

使用sed和描述的模式:

sed '/192.168.1.2/s/$/ myalias/' file


Using sedand a specific line number:

使用sed和特定的行号:

sed '2s/$/ myalias/' file

回答by John1024

An awksolution is also possible:

一个awk解决方案也是可能的:

awk '{if (/^192\.168\.1\.2 /) {
awk '/^192\.168\.1\.2 /{
awk '/search pattern/{print 
awk '==s{##代码##=##代码## OFS alias}1' s=192.168.1.2 alias=myalias file
" myalias"; next}1' file
=##代码## " myalias"}1' hosts
=##代码## " myalias"}; print}' hosts

The above reads lines from the hostsfile one by one. If the line has our IP address at the beginning, then myaliasis appended to the line. The line is then printed to stdout.

以上从hosts文件中一一读取行。如果该行以我们的 IP 地址开头,则myalias附加到该行。然后该行被打印到stdout.

Note two things. There is a space after the IP address in the ifcondition. Otherwise, the regex could match 192.168.1.20etc. Also, the periods in the IP address are escaped with backslashes. Otherwise, they could match any character.

注意两点。if条件中IP地址后有一个空格。否则,正则表达式可能匹配192.168.1.20等。此外,IP 地址中的句点用反斜杠转义。否则,它们可以匹配任何字符。

A pithier form of the solution is:

解决方案的一种更简洁的形式是:

##代码##

回答by jaypal singh

Here is another way using awk

这是另一种使用方式 awk

##代码##

回答by Scrutinizer

I would go with awk, since you can use strings and do not have to use regex, where dots would need to be escaped and anchors and/or word boundaries would need to be used. Also you can make sure the string matches a value in column 1.

我会选择awk,因为您可以使用字符串而不必使用正则表达式,其中需要转义点并且需要使用锚点和/或单词边界。您还可以确保字符串与第 1 列中的值匹配。

##代码##

Also when it is part of a larger script, it is nice to be able to use variable strings. With sedyou would need shell variables and quote trickery..

此外,当它是较大脚本的一部分时,能够使用变量字符串也很好。有了sed你需要 shell 变量和引用技巧..