简体   繁体   English

使用正则表达式提取多个值并将其重新格式化为shell oneliner中的新字符串?

[英]Extract multiple values using regex and reformat them into a new string in a shell oneliner?

Lets say for a simple example that I have a bunch of lines like this: 让我们举一个简单的例子,我有一堆这样的代码:

(1,2)
(3,4)

And I want to transform them into something like this: 我想将它们转换为如下形式:

second value: 2; first value: 1
second value: 4; first value: 3

In general I want to extract those values using a regex and then use them as variables for formatting an output string. 通常,我想使用正则表达式提取这些值,然后将它们用作格式化输出字符串的变量。

Can this be done in a shell oneliner using sed/awk or something similar? 可以使用sed / awk或类似方法在shell oneliner中完成此操作吗?

您可以使用s命令执行此操作:

sed 's/(\([0-9]*\),\([0-9]*\))/second value: \2; first value: \1/' file

In awk: 在awk中:

awk -F'[\\(\\),]' '{print "second value: "$3"; first value: "$2}'

That is delimiting each row by either a "(", ")", or ",". 那就是用“(”,“)”或“,”来分隔每行。 Then it just prints out the 3rd and 2nd values found (your two numbers). 然后,它仅打印出找到的第三个和第二个值(您的两个数字)。

使用sed以删除括号,然后打印无论是上的每一面,在所需的顺序:

sed 's/[()]//g;s/\(.*\),\(.*\)/second value: \2; first value: \1/' input_file

another sed with rev 另一个sedrev

$ rev file | sed 's/)/second value: /;s/,/; first value: /;s/(//'

second value: 2; first value: 1
second value: 4; first value: 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM