从一行中取出最后一个单词,并使用BASH在开头添加它

时间:2014-03-03 13:48:31

标签: linux bash

我们要求文本文件的内容如下:

[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"

我们想要修改的所有行都以常见的字符开头,就像在这个例子中我们要修改的所有行都以单词" 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"

这些仅供参考。原始文件包含比这些更多的数据。数百甚至数千行。

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

提前致谢。

2 个答案:

答案 0 :(得分:3)

根据我的理解,这个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 

答案 1 :(得分:2)

此命令应该完成工作

 sed -e 's/\(big[^ ]*\)\([ ]*\)var=\([^ ]*\)/\3\2msg=\1/' [your file] > [output file]

编辑:您可能需要将slach(/)更改为文件中未使用的字母