【问题标题】:Insert column with the same string in all lines在所有行中插入具有相同字符串的列
【发布时间】:2015-05-27 20:38:25
【问题描述】:

我有这个文件

mean.cel sample.cel
1  2
3  4

我想插入第二列标题的部分名称的列

这将是预期的结果

mean.cel newcolumn sample.cel
1  sample 2
3  sample 4

我该怎么做?

【问题讨论】:

    标签: awk sed


    【解决方案1】:

    我会说...

    $ awk 'NR==1{print $1, "new column", $2; next} {print $1, "sample", $2}' file
    mean.cel new column sample.cel
    1 sample 2
    3 sample 4
    

    为了使其更加健壮,允许您拥有多个字段(不仅仅是 2 个),我们可以说:

    awk '{$1 = $1 OFS (NR==1?"new column":"sample")} 1' file
    

    这里的想法是向第一个字段附加一个新值。通过使用NR,我们根据是在第一行还是在其他行来切换行为。

    【讨论】:

    • 谢谢。那行得通!我怎么能做同样的事情?,但是在多个文件中(比如说递归方式)
    • 这可能是一个新问题。至少张贴你到目前为止尝试了什么。此外,如果您的问题得到解决,您可以将答案标记为已接受。通过单击答案旁边的复选标记来将其从空心切换为绿色。如有任何问题,请参阅Help Center > Asking
    • 按照罐头上说的做,所以 +1。不过,我可能会使用 { $1 = $1 OFS "sample" } 1 使其适用于任意数量的列。
    • @Wintermute 很有趣,我采纳了你的想法,并对其进行了一些调整以做一些花哨的事情:{$1 = $1 OFS (NR==1?"new column":"sample")} 1。感谢您的想法!
    【解决方案2】:
    sed '1 {s/ / NewColumn /;b;}
    s/ / Sample /' YourFile
    
    • 基于您的示例并使用空格作为分隔符

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-03
      • 2022-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-27
      • 2021-02-14
      • 2017-11-07
      相关资源
      最近更新 更多