bash 将文本添加到制表符分隔文件中的特定列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11195153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 02:35:56  来源:igfitidea点击:

Prepending text to a specific column in a tab-delimited file?

bashsedawk

提问by E.Cross

I have a file like this (tab delimited), but many lines

我有一个这样的文件(制表符分隔),但有很多行

1314    0   0   0   0   0   3   1321    -   k63_1878003 1314    0   1314    6   171115067   64288422    64291057    4   12,131,75,1096, 0,12,143,218,   64288422,64288802,64289161,64289961,

I need to prepend a stringto column 14 of each line but keep everything else the same. Can I do this in awk or would it be better in sed?

我需要在string每行的第 14 列前加上 a ,但保持其他所有内容相同。我可以在 awk 中做到这一点还是在 sed 中会更好?

回答by Birei

Using awk. OFSprints a tab between fields in output:

使用awk. OFS在输出中的字段之间打印一个选项卡:

awk 'BEGIN { OFS = "\t" } {  = "string" ; print }' infile

回答by vergenzt

$ cat file.txt | sed 's/\(\([^\t]\+\t\)\{13\}\)/string/g'

In other words: replace (([^ ] +){13})(thirteen non-tab chunks followed by tabs) with that same text, plus your string.

换句话说:用(([^ ] +){13})相同的文本替换(十三个非制表符块后跟制表符),加上您的string.

回答by potong

This might work for you (GNU sed):

这可能对你有用(GNU sed):

sed 's/[^\t]*/string&/14' file

回答by Todd A. Jacobs

You can use concatenation to append to a field in AWK. For example:

您可以使用串联来附加到 AWK 中的字段。例如:

$ echo "foo bar baz" | awk -vOFS=$'\t' ' = "quux" '
foo quuxbar baz

In your case, you would obviously use field $13 instead. By making changes in the pattern portion, rather than the action, you are just replacing the value of the field and using the default print action for the line.

在您的情况下,您显然会改用字段 $13。通过在模式部分而不是操作中进行更改,您只需替换字段的值并使用该行的默认打印操作。