将多行字符串转换成单逗号分隔 [英] Turning multi-line string into single comma-separated

查看:147
本文介绍了将多行字符串转换成单逗号分隔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下字符串:

something1:    +12.0   (some unnecessary trailing data (this must go))
something2:    +15.5   (some more unnecessary trailing data)
something4:    +9.0   (some other unnecessary data)
something1:    +13.5  (blah blah blah)

如何将其简单化

+12.0,+15.5,+9.0,+13.5

在bash中?

推荐答案

您可以使用awksed:

awk -vORS=, '{ print $2 }' file.txt | sed 's/,$/\n/'

或者如果您想使用管道:

Or if you want to use a pipe:

echo "data" | awk -vORS=, '{ print $2 }' | sed 's/,$/\n/'

要分解它:

  • awk非常适合处理细分为字段的数据
  • -vORS=,将输出记录分隔符"设置为,,这就是您想要的
  • { print $2 }告诉awk为每个记录(行)打印第二个字段
  • file.txt是您的文件名
  • sed只是删除了结尾的,并将其转换为换行符(如果不需要换行符,可以执行s/,$//)
  • awk is great at handling data broken down into fields
  • -vORS=, sets the "output record separator" to ,, which is what you wanted
  • { print $2 } tells awk to print the second field for every record (line)
  • file.txt is your filename
  • sed just gets rid of the trailing , and turns it into a newline (if you want no newline, you can do s/,$//)

这篇关于将多行字符串转换成单逗号分隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆