developer tip

세 번째 열을 마지막 열로 인쇄하는 방법은 무엇입니까?

optionbox 2020. 8. 8. 12:28
반응형

세 번째 열을 마지막 열로 인쇄하는 방법은 무엇입니까?


DbgView 로그 파일에서 처음 두 열 (내가 관심이없는 열)을 제거하려고합니다. 행 끝까지 3 열부터 인쇄하는 예를 찾을 수없는 것 같습니다. 각 줄에는 가변 개수의 열이 있습니다.


... 또는 더 간단한 해결책 : cut -f 3- INPUTFILE올바른 구분 기호 (-d)를 추가하면 동일한 효과를 얻을 수 있습니다.


awk '{for(i=3;i<=NF;++i)print $i}' 

awk '{ print substr($0, index($0,$3)) }'

해결책은 여기에서 찾을 수 있습니다 :
http://www.linuxquestions.org/questions/linux-newbie-8/awk-print-field-to-end-and-character-count-179078/


Jonathan Feinberg 의 답변은 각 필드를 별도의 줄에 인쇄합니다. 을 사용 printf하여 동일한 줄에 출력 할 레코드를 다시 작성할 수 있지만 필드를 왼쪽으로 이동하면됩니다.

awk '{for (i=1; i<=NF-2; i++) $i = $(i+2); NF-=2; print}' logfile

awk '{$1=$2=$3=""}1' file

주의 :이 방법은 1,2,3 필드에 "공백"을 남기지 만 출력 만보고 싶다면 문제가되지 않습니다.


awk -v m="\x0a" -v N="3" '{$N=m$N ;print substr($0, index($0,m)+1)}'

이것은 주어진 필드 nr., N 앞에있는 것을 자르고, 필드 nr.N을 포함하고 원래의 간격을 유지하는 (재 형식화하지 않음) 나머지 라인을 모두 인쇄합니다. 필드의 문자열이 줄의 다른 곳에도 나타나는 경우에는 문제가되지 않습니다. 이것은 daisaa의 대답의 문제입니다.

함수를 정의하십시오.

fromField () { 
awk -v m="\x0a" -v N="$1" '{$N=m$N; print substr($0,index($0,m)+1)}'
}

다음과 같이 사용하십시오.

$ echo "  bat   bi       iru   lau bost   " | fromField 3
iru   lau bost   
$ echo "  bat   bi       iru   lau bost   " | fromField 2
bi       iru   lau bost 

출력은 후행 공백을 포함하여 모든 것을 유지합니다.

'/ n'이 레코드 구분 기호 인 파일에 잘 작동하므로 줄 안에 줄 바꿈 문자가 없습니다. 다른 레코드 구분 기호와 함께 사용하려면 다음을 사용하십시오.

awk -v m="\x01" -v N="3" '{$N=m$N ;print substr($0, index($0,m)+1)}'

예를 들면. 16 진수 문자 번호를 사용하지 않는 한 거의 모든 파일에서 잘 작동합니다. 라인 안에 1 개.


예를 들어 같은 줄에서 세 번째 이후의 열을 인쇄하려면 다음을 사용할 수 있습니다.

awk '{for(i=3; i<=NF; ++i) printf "%s ", $i; print ""}'

예를 들면 :

Mar 09:39 20180301_123131.jpg
Mar 13:28 20180301_124304.jpg
Mar 13:35 20180301_124358.jpg
Feb 09:45 Cisco_WebEx_Add-On.dmg
Feb 12:49 Docker.dmg
Feb 09:04 Grammarly.dmg
Feb 09:20 Payslip 10459 %2828-02-2018%29.pdf

다음과 같이 인쇄됩니다.

20180301_123131.jpg
20180301_124304.jpg
20180301_124358.jpg
Cisco_WebEx_Add-On.dmg
Docker.dmg
Grammarly.dmg
Payslip 10459 %2828-02-2018%29.pdf

보시다시피, 급여 명세서는 공백이 있어도 올바른 줄에 표시됩니다.


다음 줄은 어떻습니까?

awk '{$ 1 = $ 2 = $ 3 = ""; print} '파일

@ ghostdog74 제안을 기반으로합니다. 내 라인을 필터링 할 때 더 잘 작동해야합니다.

awk '/ ^ exim4-config / {$ 1 = ""; } '파일 인쇄

다음 awk 명령은 각 줄의 마지막 N 개 필드를 인쇄하고 줄 끝에 새 줄 문자를 인쇄합니다.

awk '{for( i=6; i<=NF; i++ ){printf( "%s ", $i )}; printf( "\n"); }'

아래에서 / usr / bin 디렉토리의 내용을 나열하고 마지막 3 개 행을 보유한 다음 awk를 사용하여 각 행의 마지막 4 개 열을 인쇄하는 예제를 찾으십시오.

$ ls -ltr /usr/bin/ | tail -3
-rwxr-xr-x 1 root root       14736 Jan 14  2014 bcomps
-rwxr-xr-x 1 root root       10480 Jan 14  2014 acyclic
-rwxr-xr-x 1 root root    35868448 May 22  2014 skype

$ ls -ltr /usr/bin/ | tail -3 | awk '{for( i=6; i<=NF; i++ ){printf( "%s ", $i )}; printf( "\n"); }'
Jan 14 2014 bcomps 
Jan 14 2014 acyclic 
May 22 2014 skype

음, 정규 표현식을 사용하면 동일한 효과를 쉽게 얻을 수 있습니다. 구분 기호가 공백이라고 가정하면 다음과 같습니다.

awk '{ sub(/[^ ]+ +[^ ]+ +/, ""); print }'

Perl 솔루션 :

perl -lane 'splice @F,0,2; print join " ",@F' file

These command-line options are used:

  • -n loop around every line of the input file, do not automatically print every line

  • -l removes newlines before processing, and adds them back in afterwards

  • -a autosplit mode – split input lines into the @F array. Defaults to splitting on whitespace

  • -e execute the perl code

splice @F,0,2 cleanly removes columns 0 and 1 from the @F array

join " ",@F joins the elements of the @F array, using a space in-between each element

If your input file is comma-delimited, rather than space-delimited, use -F, -lane


Python solution:

python -c "import sys;[sys.stdout.write(' '.join(line.split()[2:]) + '\n') for line in sys.stdin]" < file


awk '{a=match($0, $3); print substr($0,a)}'

First you find the position of the start of the third column. With substr you will print the whole line ($0) starting at the position(in this case a) to the end of the line.


A bit late here, but none of the above seemed to work. Try this, using printf, inserts spaces between each. I chose to not have newline at the end.

awk '{for(i=3;i<=NF;++i) printf("%s ",  $i) }'

awk '{for (i=4; i<=NF; i++)printf("%c", $i); printf("\n");}'

prints records starting from the 4th field to the last field in the same order they were in the original file


In Bash you can use the following syntax with positional parameters:

while read -a cols; do echo ${cols[@]:2}; done < file.txt

Learn more: Handling positional parameters at Bash Hackers Wiki


If its only about ignoring the first two fields and if you don't want a space when masking those fields (like some of the answers above do) :

awk '{gsub($1" "$2" ",""); print;}' file

awk '{$1=$2=""}1' FILENAME | sed 's/\s\+//g'

First two columns are cleared, sed removes leading spaces.


awk '{print ""}{for(i=3;i<=NF;++i)printf $i" "}'

In AWK columns are called fields, hence NF is the key

all rows:

awk -F '<column separator>' '{print $(NF-2)}' <filename>

first row only:

awk -F '<column separator>' 'NR<=1{print $(NF-2)}' <filename>

참고URL : https://stackoverflow.com/questions/1602035/how-to-print-third-column-to-last-column

반응형