linux 简单的awk命令问题(FS、OFS相关)

wribegjk  于 5个月前  发布在  Linux
关注(0)|答案(3)|浏览(77)

我试图重新组织一个文件的格式,其中包含:

>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

字符串
我的命令是:

awk '{FS="|";OFS="\t"} {print $1,$2,$3,$4,$5}'


下面是输出:

>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


除了第一行,其他行都很好。我不明白为什么会这样。
有人能帮我吗?谢谢!

ma8fv8wu

ma8fv8wu1#

简短回答

FSOFS设置得太晚,不会影响第一行,请使用类似这样的代码:

awk '{print $1,$2,$3,$4,$5}' FS='|' OFS='\t'

字符串
你也可以使用这个简短的版本:

awk -v FS='|' -v OFS='\t' '$1=$1'

稍长的回答

这不起作用,因为awk在设置FSOFS时已经执行了记录/字段拆分。您可以通过将$0设置为$0来强制重新拆分,例如:

awk '{FS="|";OFS="\t";$0=$0} {print $1,$2,$3,$4,$5}'


传统的方法是1.在BEGIN子句中设置FS和其他,2.通过-v VAR=VALUE表示法设置它们,或者3.将它们作为VAR=VALUE追加到脚本之后。我喜欢的风格是最后一种:

awk '{print $1,$2,$3,$4,$5}' FS='|' OFS='\t'


请注意,在设置-v和postscript变量之间存在显着差异。-v将在BEGIN子句之前设置变量,而postscript变量设置则在BEGIN子句之后设置。

kuhbmx9i

kuhbmx9i2#

尝试:

awk 'BEGIN{FS="|";OFS="\t"} {print $1,$2,$3,$4,$5}'

字符串

5ssjco0h

5ssjco0h3#

我知道我来晚了,但你也可以使用tr命令:tr "|" "\t"

相关问题