2017-03-16 3 views
0

다른 파일에 나열된 이름으로 일부 열을 추출하려고합니다. 리눅스 - 텍스트 길이 제한

나는 다음과 같은 링크로이 유용한 코드를 발견 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" 

이전에 링크에서 동일한 예를 사용했습니다. {0 : 3 $ F}, 그것은 나에게 구문 오류가 있습니다 내가 원하는

$ 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 

입니다. 감사합니다. 도와주세요. man 1 awk에서

답변

0

:

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)