【问题标题】:replace column in file with portion of filename linux [closed]用文件名linux的一部分替换文件中的列[关闭]
【发布时间】:2013-12-03 10:58:12
【问题描述】:

我有大量以下列方式命名的数千个文件:

Track_0000000_extract.txt

其中的零可以替换为任何数值。

这些文件的内容如下:

1 0 138.7936 26.4674 -1.517 7.225 0 1 95564.477 100997.425 267127.576 44.585 215803.887 
1 6 138.4649 27.8692 -2.318 4.902 0 1 96308.418 101000.391 240804.857 40.122 239866.492 
1 12 137.956 28.8204 -2.196 6.239 0 1 96602.983 100980.098 193555.58 43.644 227623.588 
1 18 137.4698 30.031 -2.734 6.457 0 1 96763.473 100962.086 189049.294 42.996 132256.485 
1 24 136.857 31.2838 -2.595 1.886 0 1 97331.108 100934.865 120323.785 39.545 177050.848 
1 30 136.2677 31.6498 -5.708 -2.484 0 1 97295.779 100920.752 144810.457 37.85 23238.046 

我想用文件名中的数值替换每个文件第一列中的数字 1。是否可以一次轻松地在 linux shell 中为我所有的数千个文件执行此操作?

谢谢, 金佰利

【问题讨论】:

    标签: linux replace find


    【解决方案1】:

    这将创建具有.new 扩展名的文件,其中第一列被数值替换。

    #!/bin/sh
    for file in Track_*_extract.txt
    do
        num=${file#Track_}
        num=${num%_extract.txt}
        awk -v num=$num '{ $1=num; print }' < $file > $file.new
    done
    

    如果您希望仅当第一列中的数字是数字 1 时才将其替换为数值 - 我不清楚您想要什么 - 然后使用:

    #!/bin/sh
    for file in Track_*_extract.txt
    do
        num=${file#Track_}
        num=${num%_extract.txt}
        awk -v num=$num '{ if ($1 == 1) { $1=num }; print }' < $file > $file.new
    done
    

    【讨论】:

    • 您的第一个建议非常适合我的情况。谢谢!对于将来出现的问题,我会牢记这一点。这些对我来说似乎是一个普遍的问题。谢谢!
    【解决方案2】:

    单行:

    find -name 'Track*_extract.txt' | \
          cut -d_ -f2 | \
          xargs -n 1 -I @ sed -i 's!^[^ ]*!'@'!' Track_@_extract.txt 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多