sed替换无标题的多个tsv文件的第n列 [英] Sed replace nth column of multiple tsv files without header

查看:78
本文介绍了sed替换无标题的多个tsv文件的第n列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有多个tsv文件,我只想在第二列(标题以外的所有位置)中添加"XX"字符,并将其保存到同一文件中.

Here are multiple tsv files, where I want to add 'XX' characters only in the second column (everywhere except in the header) and save it to this same file.

输入:

$ls
file1.tsv file2.tsv file3.tsv

$head -n 4 file1.tsv
a   b   c
James England  25
Brian France   41
Maria France   18

通缉令:

a   b   c
James X1_England  25
Brian X1_France   41
Maria X1_France   18

我尝试了此操作,但结果未保存在文件中,并且无法进行简单的重定向:

I tried this, but the result is not kept in the file, and a simple redirection won't work:

   # this works, but doesn't save the changes 
    i=1
    for f in *tsv
      do awk '{if (NR!=1) print $2}’ $f | sed "s|^|X${i}_|" 
      i=$((i+1))
    done

    # adding '-i' option to sed: this throws an error but would be perfect (sed no input files error)
    i=1
    for f in *tsv
      do awk '{if (NR!=1) print $2}’ $f | sed -i "s|^|T${i}_|" 
      i=$((i+1))
    done 

我们将不胜感激.

推荐答案

AWK解决方案:

awk -i inplace 'BEGIN { FS=OFS="\t" } NR!=1 { $2 = "X1_" $2 } 1' file1.tsv

输入:

a   b       c
James       England 25
Brian       France  41
Maria       France  18

输出:

a   b       c
James       X1_England      25
Brian       X1_France       41
Maria       X1_France       18

这篇关于sed替换无标题的多个tsv文件的第n列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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