bash - 在 bash 脚本中使用多字符定界符

标签 bash ifs

我有一个文本文件,其中的数据格式为:

Number of Iterations: 150
Average time is 45 ms
Average time for collisions is 50 ms
Total time is 95 ms
....

有多个此类文件。我必须阅读所有这些文件并制作一个 csv 文件,其中将包含以下形式的条目:

150,45,50,95
200,40,60,100 
...
...

每一行对应一个txt文件。
我正在编写一个 bash 脚本来从这些数据生成 CSV 文件。
我只想读取文本文件中的数字。
对于第一行,我尝试使用

    IFS =": " read w1 w2

但是它通过使用空格和':'作为分隔符来分割行
当我使用

    IFS=":" 

在我不想要的 150 前面打印了一个额外的空间。
我该怎么做呢?
同样在第二行中,我想使用“is”作为分隔符。允许吗?
谢谢

最佳答案

你可以使用这个 awk:

cat file
Number of Iterations: 150
Average time is 45 ms
Average time for collisions is 50 ms
Total time is 95 ms
Number of Iterations: 200
Average time is 40 ms
Average time for collisions is 60 ms
Total time is 100 ms

awk '/^Total/{p=1} {gsub(/[^0-9]+/, ""); a[++i]=$0}
     p{print a[1], a[2], a[3], a[4]; p=0; delete a; i=0}' OFS=, file
150,45,50,95
200,40,60,100

关于bash - 在 bash 脚本中使用多字符定界符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21643727/

相关文章:

shell - 如何在 KornShell (ksh) 中正确保存 IFS

linux - 在 Linux 中删除 10 天前的旧文件夹

linux - 如何在所有目录中的特定文件中循环 shell 脚本?

linux - 使用 Bash 用 IFS 分割字符串?

date - BASH:你如何执行 "split"日期命令?

linux - IFS 和命令替换

string - 如何使用 Bash 测试文件中是否存在字符串?

bash - 查看 bash 变量的确切内容? (hexdump 没有帮助)

在单引号上使用 IFS 拆分 Linux bash 字符串

bash: `read` 似乎不支持 IFS