텍스트 파일에서 n 번째 열 가져 오기
텍스트 파일이 있습니다.
1 Q0 1657 1 19.6117 Exp
1 Q0 1410 2 18.8302 Exp
2 Q0 3078 1 18.6695 Exp
2 Q0 2434 2 14.0508 Exp
2 Q0 3129 3 13.5495 Exp
나는 다음과 같이 모든 줄의 두 번째와 네 번째 단어를 취하고 싶습니다.
1657 19.6117
1410 18.8302
3078 18.6695
2434 14.0508
3129 13.5495
이 코드를 사용하고 있습니다.
nol=$(cat "/path/of/my/text" | wc -l)
x=1
while [ $x -le "$nol" ]
do
line=($(sed -n "$x"p /path/of/my/text)
echo ""${line[1]}" "${line[3]}"" >> out.txt
x=$(( $x + 1 ))
done
작동하지만 매우 복잡하고 긴 텍스트 파일을 처리하는 데 오랜 시간이 걸립니다.
이 작업을 수행하는 더 간단한 방법이 있습니까?
iirc :
cat filename.txt | awk '{ print $2 $4 }'
또는 의견에서 언급했듯이 :
awk '{ print $2 $4 }' filename.txt
다음 cut
명령을 사용할 수 있습니다 .
cut -d' ' -f3,5 < datafile.txt
인쇄물
1657 19.6117
1410 18.8302
3078 18.6695
2434 14.0508
3129 13.5495
그만큼
-d' '
-의미,space
구분자로 사용-f3,5
-세 번째 및 다섯 번째 열 가져 오기 및 인쇄
순수한 셸 솔루션으로 대용량 파일 의 cut
경우 훨씬 빠릅니다 . 파일이 여러 공백으로 구분 된 경우 다음과 같이 먼저 제거 할 수 있습니다.
sed 's/[\t ][\t ]*/ /g' < datafile.txt | cut -d' ' -f3,5
여기서 (gnu) sed는 tab
또는 space
문자를 단일 space
.
변형의 경우-여기에 펄 솔루션도 있습니다.
perl -lanE 'say "$F[2] $F[4]"' < datafile.txt
완전성을 위해 :
while read _ _ one _ two _; do
echo "$one $two"
done < file.txt
_
임의의 변수 (예 :) 대신 junk
사용할 수도 있습니다. 요점은 열을 추출하는 것입니다.
데모:
$ while read _ _ one _ two _; do echo "$one $two"; done < /tmp/file.txt
1657 19.6117
1410 18.8302
3078 18.6695
2434 14.0508
3129 13.5495
하나 더 간단한 변형-
$ while read line
do
set $line # assigns words in line to positional parameters
echo "$3 $5"
done < file
파일에 n 줄이 포함되어 있으면 스크립트는 파일을 n 번 읽어야합니다 . 따라서 파일 길이를 두 배로 늘리면 스크립트가 수행하는 작업의 양이 네 배로 늘어납니다. 원하는 작업은 순서대로 줄을 반복하는 것이므로 거의 모든 작업이 버려집니다.
대신, 파일의 행을 반복하는 가장 좋은 방법 while
은 condition-command가 read
내장 된 루프 를 사용하는 것입니다 .
while IFS= read -r line ; do
# $line is a single line of the file, as a single string
: ... commands that use $line ...
done < input_file.txt
귀하의 경우, 라인을 배열로 나누고 싶고 read
내장은 실제로 원하는 배열 변수를 채우기위한 특별한 지원을 가지고 있기 때문에 다음과 같이 작성할 수 있습니다.
while read -r -a line ; do
echo ""${line[1]}" "${line[3]}"" >> out.txt
done < /path/of/my/text
or better yet:
while read -r -a line ; do
echo "${line[1]} ${line[3]}"
done < /path/of/my/text > out.txt
However, for what you're doing you can just use the cut
utility:
cut -d' ' -f2,4 < /path/of/my/text > out.txt
(or awk
, as Tom van der Woerdt suggests, or perl
, or even sed
).
If you are using structured data, this has the added benefit of not invoking an extra shell process to run tr
and/or cut
or something. ...
(Of course, you will want to guard against bad inputs with conditionals and sane alternatives.)
...
while read line ;
do
lineCols=( $line ) ;
echo "${lineCols[0]}"
echo "${lineCols[1]}"
done < $myFQFileToRead ;
...
참고URL : https://stackoverflow.com/questions/17137269/take-nth-column-in-a-text-file
'Program Tip' 카테고리의 다른 글
핀치를 감지하는 가장 간단한 방법 (0) | 2020.10.25 |
---|---|
Makefile-구분 기호 누락 (0) | 2020.10.25 |
IntelliJ 새 프로젝트-Maven Archetype 목록이 비어 있음 (0) | 2020.10.25 |
내 스크립트에서 사용할 사용자 지정 형식을 PowerShell에서 만들려면 어떻게해야합니까? (0) | 2020.10.25 |
WPF DataGrid에서 ComboBoxColumn의 ItemsSource 바인딩 (0) | 2020.10.25 |