Linux 简单的 awk 命令问题(FS、OFS 相关)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16203336/
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
Simple awk command issue (FS, OFS related)
提问by olala
I tried to reorganize the format of a file containing:
我试图重新组织包含以下文件的格式:
>Humanl|chr16:86430087-86430726 | element 1 | positive
>Humanl|chr16:85620095-85621736 | element 2 | negative
>Humanl|chr16:80423343-80424652 | element 3 | negative
>Humanl|chr16:80372593-80373755 | element 4 | positive
>Humanl|chr16:79969907-79971297 | element 5 | negative
>Humanl|chr16:79949950-79951518 | element 6 | negative
>Humanl|chr16:79026563-79028162 | element 7 | negative
>Humanl|chr16:78933253-78934686 | element 9 | negative
>Humanl|chr16:78832182-78833595 | element 10 | negative
My command is:
我的命令是:
awk '{FS="|";OFS="\t"} {print ,,,,}'
Here is the output:
这是输出:
>Human|chr16:86430087-86430726 | element 1 |
>Human chr16:85620095-85621736 element 2 negative
>Human chr16:80423343-80424652 element 3 negative
>Human chr16:80372593-80373755 element 4 positive
>Human chr16:79969907-79971297 element 5 negative
>Human chr16:79949950-79951518 element 6 negative
>Human chr16:79026563-79028162 element 7 negative
>Human chr16:78933253-78934686 element 9 negative
>Human chr16:78832182-78833595 element 10 negative
Every line works fine except for the first line. I don't understand why this happened.
除了第一行之外,每一行都可以正常工作。我不明白为什么会这样。
Can someone help me with it? Thanks!
有人可以帮我吗?谢谢!
采纳答案by Thor
Short answer
简答
FS
and OFS
are set too late to affect the first line, use something like this instead:
FS
并且OFS
设置得太晚而无法影响第一行,请改用以下内容:
awk '{print ,,,,}' FS='|' OFS='\t'
You can also use this shorter version:
您还可以使用这个较短的版本:
awk -v FS='|' -v OFS='\t' '='
A bit longer answer
有点长的答案
It doesn't work because awk has already performed record/field splitting at the time when FS
and OFS
are set. You can force a re-splitting by setting $0
to $0
, e.g.:
它不起作用,因为 awk 在设置FS
和时已经执行了记录/字段拆分OFS
。您可以通过设置$0
为强制重新拆分$0
,例如:
awk '{FS="|";OFS="\t";awk '{print ,,,,}' FS='|' OFS='\t'
=awk 'BEGIN{FS="|";OFS="\t"} {print ,,,,}'
} {print ,,,,}'
The conventional ways to do this are 1. set FS
and others in the BEGIN
clause, 2. set them through the -v VAR=VALUE
notation, or 3. append them after the script as VAR=VALUE
. My preferred style is the last alternative:
执行此操作的常规方法是 1.FS
在BEGIN
子句中设置和其他,2. 通过-v VAR=VALUE
符号设置它们,或 3. 将它们附加在脚本之后作为VAR=VALUE
。我喜欢的风格是最后一种选择:
Note that there is a significant difference between when -v
and post-script variables are set. -v
will set variables before the BEGIN
clause whilst post-script setting of variables are set just after the BEGIN
clause.
请注意,-v
设置when和 post-script 变量之间存在显着差异。-v
将在BEGIN
子句之前设置变量,而在子句之后设置变量的脚本后设置BEGIN
。
回答by Kent
try:
尝试:
##代码##