gpt4 book ai didi

linux - 使用 BASH 从一行中取出最后一个单词并将其添加到开头

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:29:01 25 4
gpt4 key购买 nike

我们有一个要求,我们的文本文件的内容是这样的:

[some-section-1]
big_msg_line1 var=random_value1
big_msg_line2 var=random_value2
big_msg_line3 var=random_value3

[some-section-2]
"lots of irrelevant data"

[some-section-3]
"lots of irrelevant data"

[some-section-4]
big_msg_line4 var=random_value4
big_msg_line5 var=random_value5
big_msg_line6 var=random_value6
big_msg_line7 var=random_value7
big_msg_line8 var=random_value8

[some-section-5]
"lots of irrelevant data"

我们要修改的所有行都以公共(public)字符开头,就像在这个例子中我们要修改的所有行都以单词“big”开头。我们想把它改成这样:

[some-section-1]
random_value1 msg=big_msg_line1
random_value2 msg=big_msg_line2
random_value3 msg=big_msg_line3

[some-section-2]
"lots of irrelevant data"

[some-section-3]
"lots of irrelevant data"

[some-section-4]
random_value4 msg=big_msg_line4
random_value5 msg=big_msg_line5
random_value6 msg=big_msg_line6
random_value7 msg=big_msg_line7
random_value8 msg=big_msg_line8

[some-section-5]
"lots of irrelevant data"

这些仅供引用。原始文件包含的数据比这些多得多。成百上千行。

我目前正在使用 for 循环执行此操作,读取每一行,剪切值,按照我想要的方式格式化它们,然后放入单独的文件中,然后用新文件替换原始文件。有没有办法使用一些衬里来实现这一目标?那真的会有很大的帮助。希望我的问题很清楚。

提前致谢。

最佳答案

据我所知,这个 awk 单行代码可以完成这项工作:

cat a
[some-section-1]
big_msg_line1 var=random_value1
big_msg_line2 var=random_value2
big_msg_line3 var=random_value3

[some-section-2]
lots of irrelevant data

[some-section-3]
lots of irrelevant data

[some-section-4]
big_msg_line4 var=random_value4
big_msg_line5 var=random_value5
big_msg_line6 var=random_value6
big_msg_line7 var=random_value7
big_msg_line8 var=random_value8

[some-section-5]
lots of irrelevant data

这个:

awk '{FS="var="; if ($1~/big/) { print $2"\tmsg="$1} else {print }}' a

给予

[some-section-1]
random_value1 msg=big_msg_line1
random_value2 msg=big_msg_line2
random_value3 msg=big_msg_line3

[some-section-2]
lots of irrelevant data

[some-section-3]
lots of irrelevant data

[some-section-4]
random_value4 msg=big_msg_line4
random_value5 msg=big_msg_line5
random_value6 msg=big_msg_line6
random_value7 msg=big_msg_line7
random_value8 msg=big_msg_line8

[some-section-5]
lots of irrelevant data

关于linux - 使用 BASH 从一行中取出最后一个单词并将其添加到开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22148495/

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