简体   繁体   中英

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?

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

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

In 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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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