gpt4 book ai didi

linux - 查找、替换或插入 - 命令行

转载 作者:太空宇宙 更新时间:2023-11-04 09:31:10 25 4
gpt4 key购买 nike

我有一个类似的列表:

What do you want to do?
Import a text file by opening it in Excel
Import a text file by connecting to it
Export data to a text file by saving it
Change the delimiter that is used in a text file
Change the separator in all .csv text files

使用 SED 我可以在“连接”上找到匹配项并替换该行:

 sed 's^.*connecting.*^Import a text file by opening it^g' crontab

这应该将上面的列表更改为:

What do you want to do?
Import a text file by opening it in Excel
Import a text file by opening it
Export data to a text file by saving it
Change the delimiter that is used in a text file
Change the separator in all .csv text files

但是我需要做的是:

如果存在包含单词 connecting 的行,则替换该行,如果该行不存在,则将其作为新行添加到列表的末尾。

我知道我可以做 echo "Import a text file by opening it">> list 这会将行添加到列表的末尾,但无论如何我可以在一个命令 ?或可以在一个实例中运行的命令?

谢谢

最佳答案

一个简单的方法是使用awk:

awk 'BEGIN { s = "Import a text file by opening it" } /connecting/ { $0 = s; n = 1 } 1; END { if(!n) print s }' filename

工作原理如下:

BEGIN {                                    # Before anything else:
s = "Import a text file by opening it" # Remember the string by a shorter
# name so we don't have to repeat it
}
/connecting/ { # If a line contains "connecting",
$0 = s # replace the line with that string
n = 1 # and raise a flag that we've done so.
}
1 # print
END { # in the end:
if(!n) { # If the string wasn't yet printed,
print s # do it now.
}
}

或者,您可以使用 sed 的保持缓冲区。例如:

sed '1 { x; s/.*/Import a text file by opening it/; x; }; /connecting/ { s/.*//; x; }; $ { G; s/\n$//; }' filename

工作原理如下:

1 {                                        # while processing the first line
x # swap hold buffer, pattern space
s/.*/Import a text file by opening it/ # write text to pattern space
x # swap back.
} # Now the hold buffer contains the
# line we want to insert, and the
# pattern space the first line.

/connecting/ { # For all lines: If a line contains
# "connecting"
s/.*// # empty the pattern space
x # swap in hold buffer.
# If this happened, the hold buffer
# will be empty and the pattern space
# will contain "Import a ..."
}
$ { # Last line:
G # Append hold buffer to pattern space.
# If the hold buffer is empty (i.e.,
# was used somewhere else), this
# appends a newline, so
s/\n$// # remove it if that happened.
}

请注意,sed 代码取决于只有一行包含“connecting”这一事实。如果有更多这样的行,它们将被空行替换,因为当第二行出现时保持缓冲区是空的。可以处理这种情况,但您必须决定其中应该发生什么。既然你在评论中回复说只有这样一行,我觉得没有必要去猜测。

关于linux - 查找、替换或插入 - 命令行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31179127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com