【问题标题】:How to use space as field separator using awk?如何使用 awk 将空格用作字段分隔符?
【发布时间】:2017-08-09 11:55:31
【问题描述】:

在此我尝试将列与字段分隔符一起输出。

但在我的情况下它失败了。

awk.txt(Input file)

Sr No Name Sub Marks
1) Amit Physics 80
2) Rahul Maths 90
3) Shyam Biology 87
4) Kedar English 85
5) Hari History 89
我尝试的

awk 命令如下:-

 awk -F ' ' '{print $2 $3;}' awk.txt > output.txt

获得的输出:

NoName
AmitPhysics
RahulMaths
ShyamBiology
KedarEnglish
HariHistory

预期输出:

    Name Sub 
    Amit Physics 
    Rahul Maths 
    Shyam Biology 
    Kedar English 
    Hari History 

【问题讨论】:

  • 您是在 DOS 机器上运行命令还是)从中复制粘贴?您的单引号是 unicode 字符串,可能不适用于 linux
  • 我在 linux 终端 @Inian 中运行它
  • 好的,但是引号是错误的,看{}周围的引号和-F之后的引号是不正确的
  • 除了已经存在的有用建议之外,您还会得到“NoName”而不是“NameSub”,因为第一列的标题显然是“Sr No”,但您使用空格作为分隔符.不要将分隔符作为字符放在字段值中。

标签: awk


【解决方案1】:
awk '{print $3,$4;}' awk.txt > output.txt

不需要指明字段分隔符。字段编号从 1 开始,因此您需要第三个和第四个字段。对于打印 OFS(输出字段分隔符),请使用逗号。

或:

awk 'BEGIN{FS=OFS=" ";}{print $3,$4;}' awk.txt > output.txt

【讨论】:

    猜你喜欢
    • 2011-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-25
    • 2017-10-23
    • 2015-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多