【问题标题】:Bash: how to split a line by a delimiter and print each element on a new line?Bash:如何用分隔符分割一行并将每个元素打印在新行上?
【发布时间】:2019-11-15 22:20:55
【问题描述】:

我有一个 CSV 文件,其标题包含 2000 多列。我希望只读取第一行然后将其拆分,并在新行中打印每个列名,以便我可以通过 grep 查看列是否存在。我被卡住了

head -n 1 file.csv | ### what do do here? ### | grep var_i_want

【问题讨论】:

    标签: bash awk sed


    【解决方案1】:

    你可以使用tr,比如:

    head -n 1 file.csv | tr "," "\n"
    

    这不会处理带有逗号的字段。如果你可以访问python,你可以这样做:

    head -n 1 file.csv | python -c 'import csv,sys; print("\n".join(csv.reader(sys.stdin).next()))'
    

    【讨论】:

      【解决方案2】:

      您能否尝试以下操作,awk 应该足够快(因为您提到了一个 .csv 输入文件,所以我将字段分隔符作为 , 如果您没有逗号作为字段分隔符,那么您也可以从以下代码中删除FS="," 部分)。

      awk 'BEGIN{FS=",";OFS="\n"} FNR==1{$1=$1;print;exit}' Input_file
      

      由于您还没有发布示例,所以考虑以下是 Input_file:

      cat Input_file
      a,b,c,d
      1,2,3,4,5,
      

      现在运行代码后会得到以下输出。

      awk 'BEGIN{FS=",";OFS="\n"} FNR==1{$1=$1;print;exit}' Input_file
      a
      b
      c
      d
      

      由于我使用条件FNR==1,所以它只会读取第一行,然后我使用exit,它会在完成 Line1 上的操作后退出程序本身,并且不会读取整个 Input_file。

      说明:为上述代码添加说明。

      awk '             ##Starting awk program from here.
      BEGIN{            ##Starting BEGIN section from here.
        FS=","          ##Setting FS as comma here.
        OFS="\n"        ##Setting OFS as a new line here.
      }
      FNR==1{           ##Checking condition if this is first line then do following.
        $1=$1           ##Re-arranging first field to make OFS into picture, since by default OFS is space and I am setting it as a new line.
        print           ##Printing current line here.
        exit            ##exit will make program exit.
      }
      ' Input_file      ##Mentioning Input_file name here.
      

      【讨论】:

      • 你能详细说明一下$1=$1这一行吗?我可以想象它改变了第一个字段和其余字段之间的分隔符,但是其他字段呢?
      • @User10482,当然,$1=$1 会将 OFS 的新值应用于当前行。这就像将第一个字段重新分配给自己以简单地对其应用 OFS(详细解释也附在答案中),干杯。
      【解决方案3】:

      基于sed 的方法:

      $ sed -n '1s/,/\n/gp' file.csv
      a
      b
      c
      d
      

      解释:

      • -n:默认不打印。
      • 1s/... 在第一行,替换
      • s/,/\n/g:用换行符替换所有逗号
      • .../gp:替换成功则打印。

      如果标题行可能只包含一列,请使用

       $ sed -rn '1s/($|,)/\n/gp' file.csv
      a
      b
      c
      d
      <an empty line is printed here>
      

      【讨论】:

        【解决方案4】:

        在不同的行中打印每个列名:

        IFS=,; for col in $(head -n1 file.csv); do echo $col; done
        

        在标题中搜索列名:

        head -n 1 file.csv | grep -o col_name
        

        【讨论】:

          猜你喜欢
          • 2016-07-30
          • 2019-06-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-03-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多