
파일이 있습니다:
sample_1 sample_2 sample_3 category subcategory class levels
52 59 80 wild animal herbe small
25 65 71 pet insect
원하는 출력을 얻기 위해 세 번째 열 이후의 모든 열을 병합하고 싶습니다.
sample_1 sample_2 sample_3 info
52 59 80 wild|animal|herbe|small
25 65 71 pet|insect
답변1
다음 awk 스크립트를 고려해보세요:
awk 'BEGIN { IFS=OFS="\t" }
NR==1 { print "sample_1" OFS "sample_2" OFS "sample_3" OFS "info" }
NR >1 { four=$4
for(i=5; i <= NF; i++) four=four"|"$i
print $1 OFS $2 OFS $3 OFS four }' input
스크립트는 세 부분으로 나뉩니다.
BEGIN
-- 스크립트는 입력을 읽기 전에 입력 및 출력 필드 구분 기호를 탭으로 설정합니다.NR==1
-- 표시된 대로 제목이 다시 작성됩니다.NR >1
-- 탭(OFS)과 결합하기 위해 4개의 필드를 축소합니다. 필드 #4로 새 값을 초기화한 다음 나머지 필드를 반복하고 해당 값에 파이프 문자를 추가합니다. 루프가 완료된 후 다시 조립된 라인을 인쇄합니다.
답변2
줄에 후행 공백이 없으면 GNU sed를 사용하여 빠르게 수행할 수 있습니다.
$ sed -E -e 's/\s+/\|/4g' -e '1s/\S*$/info/' file
sample_1 sample_2 sample_3 info
52 59 80 wild|animal|herbe|small
25 65 71 pet|insect
괜찮다면하다뒤에 공백이 있습니다. 먼저 공백을 제거할 수 있습니다.
sed -E -e 's/ +$//' -e 's/\s+/\|/4g' -e '1s/\S*$/info/' file
답변3
다음 명령을 사용해보십시오. 훌륭하게 작동합니다.
awk 'NR >1{$4=$4$5$6$7;$5=$6=$6=$7="";print $0}' filename| sed '1i sample_1 sample_2 sample_3 info '| awk '{printf "%s%10s%10s%30s\n",$1,$2,$3,$4}'
산출
sample_1 sample_2 sample_3 info
52 59 80 wildanimalherbesmall
25 65 71 petinsect