【问题标题】:Linux - limit the length of textLinux - 限制文本长度
【发布时间】:2017-03-17 00:22:17
【问题描述】:

我想按列在不同文件中的名称提取一些列。

我在以下链接中找到了这个有用的代码:AWK extract columns from file based on header selected from 2nd file

我尝试编辑一些以打印标题并限制标题的长度。

#!/bin/bash

DATAFILE=${1:-data.txt}
COLUMNFILE=${2:-list.txt}

awk -v colsFile="$COLUMNFILE" '
   BEGIN {
     j=1
     while ((getline < colsFile) > 0) {
        col[j++] = $1
     }
     n=j-1;
     close(colsFile)
     for (i=1; i<=n; i++) s[col[i]]=i
   }
   NR==1 {
     for (f=1; f<=NF; f++)
       if ($f in s) c[s[$f]]=f
       printf ${$f:0:3}
   }
   { sep=""
     for (f=1; f<=n; f++) {
       printf("%c%s",sep,$c[f])
       sep=" "
     }
     print ""
   }
' "$DATAFILE"

我之前在链接中使用了相同的示例。

$ cat data.txt
ID,head1,head2,head3,head4
1,25.5,1364.0,22.5,13.2
2,10.1,215.56,1.15,22.2

$ cat list.txt
ID
head1
head4

$ dataExtractor.sh data.txt list.txt
1,25.5,13.2
2,10.1,22.2

我想要的输出是

ID,hea,hea
1,25.5,13.2
2,10.1,22.2

在我编辑代码以包含 ${$f:0:3} 后,它给了我一个语法错误。 请帮我解决这个问题,谢谢!

【问题讨论】:

    标签: linux


    【解决方案1】:

    来自man 1 awk

       substr(s, i [, n])      Return  the  at most n-character substring of s
                               starting at i.  If n is omitted, use  the  rest
                               of s.
    

    ...

    substr($f, 0, 3)
    

    【讨论】:

      猜你喜欢
      • 2015-09-13
      • 1970-01-01
      • 2010-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多