简体   繁体   中英

How to use regex using awk

I have a file, say test.txt which looks like a json and it contains a single line of data:

{"a":"b"},{"c":"d, e, f"},{..} and so on

I need to save all the data within each pair of braces in a different file in separate lines.

For eg: result.txt having

"a":"b"
"c":"d, e, f"

I used awk with regex in bash scripting

awk '/\{(.*?)\}/' test.txt  > result.txt

But instead of cropping up individual braces, it's printing the exact test file as it is.

Can anyone say what's going wrong?

echo '{"a":"b"},{"c":"d e f"},{..}' |awk -v RS="{|}" '{gsub(/,/,"")} /./{print $0}'
"a":"b"
"c":"d e f"
..

Note: It's a good idea to use json editing tools like jq to play around with json files.

或者,您可以使用带有环视的grep来仅捕获大括号之间的值:

grep -oP '(?<={).*?(?=})' test.txt > result.txt

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