【问题标题】:Proces a text file shell script that have numbers and strings [closed]处理具有数字和字符串的文本文件 shell 脚本 [关闭]
【发布时间】:2015-10-17 18:21:20
【问题描述】:

我有一个这种形式的文件:

2ThroughputRule.js:128 bw   3545891 3545891 3545891
ThroughputRule.js:128 bw    124776  1835334 1151111
ThroughputRule.js:128 bw    1959606 1876758 2435492
ThroughputRule.js:128 bw    3213333 1765905 2979981
2ThroughputRule.js:128 bw   1985927 2386289 2284143

我想要一种处理文件的方法,以便 shell 脚本可以读取每行的第一个字符,如果它找到一个数字,则将该行从数字旁边复制该行的次数,直到下面的 EOL。

比如我有

2ThroughputRule.js:128 bw 3545891 3545891 3545891

结果是

2ThroughputRule.js:128 bw 3545891 3545891 3545891

ThroughputRule.js:128 bw 3545891 3545891 3545891

如果我有

4ThroughputRule.js:128 bw 3545891 3545891 3545891

ThroughputRule.js:128 bw 3545891 3545891 3545891

ThroughputRule.js:128 bw 3545891 3545891 3545891

ThroughputRule.js:128 bw 3545891 3545891 3545891

有可能吗?

【问题讨论】:

  • 我编辑了我的问题,谢谢

标签: linux bash file shell text


【解决方案1】:

你可以试试这个程序。另存为pr.awk。并运行awk -f pr.awk test.txt

function force_num(x) {return x+0}

match($0, "^[0-9]+") {
    n   = substr($0, RSTART, RLENGTH)
    n   = force_num(n)

    rst = substr($0, RSTART + RLENGTH)
    for (i=1; i<=n; i++)
        print rst

    next
}

{
    print
}

【讨论】:

  • 但有时 2 并不总是不同的数字,我该怎么办?
  • @MiguelA.AguayoOrtuño 查看更新。
【解决方案2】:

你可以使用这个 awk 命令:

awk '1; /^[0-9]/{print substr($0,2)}' file
2ThroughputRule.js:128 bw   3545891 3545891 3545891
ThroughputRule.js:128 bw   3545891 3545891 3545891
ThroughputRule.js:128 bw    124776  1835334 1151111
ThroughputRule.js:128 bw    1959606 1876758 2435492
ThroughputRule.js:128 bw    3213333 1765905 2979981
2ThroughputRule.js:128 bw   1985927 2386289 2284143
ThroughputRule.js:128 bw   1985927 2386289 2284143

命令分解:

1;                 # prints each record
/^[0-9]/           # if a row starts with a digit
print substr($0,2) # prints from 2nd char onward in next line

【讨论】:

    【解决方案3】:

    您可以使用grep 匹配字符串,使用cut 删除字符:

    grep "^[0-9]" file | cut -c 2-
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-14
      • 2011-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-05
      • 2013-08-05
      相关资源
      最近更新 更多