![배열의 단어를 일치시켜 파일을 한 줄씩 분리합니다.](https://linux55.com/image/88185/%EB%B0%B0%EC%97%B4%EC%9D%98%20%EB%8B%A8%EC%96%B4%EB%A5%BC%20%EC%9D%BC%EC%B9%98%EC%8B%9C%EC%BC%9C%20%ED%8C%8C%EC%9D%BC%EC%9D%84%20%ED%95%9C%20%EC%A4%84%EC%94%A9%20%EB%B6%84%EB%A6%AC%ED%95%A9%EB%8B%88%EB%8B%A4..png)
다음은 내 입력 데이터의 예입니다.
$9.99,Titan the Power,www.example.com,565654
$15.99,Conan The Barbarian,www.sure.com,565438
$1.99,Julia Cesar,www.bfg.com,69722
입력 파일에서 배열을 만든 다음 변수에서 제목을 분리하기 위해 이 코드를 작성했습니다 $f2
.
#!/bin/bash
input="/home/test/Documents/Scripts/test.csv"
readarray myarray < $input
# Sends all of arrays into while loop which read each line by line
echo "${myarray[@]}" | while IFS=',' read -r f1 f2 f3 f4
do
# echo field 2 of each line
echo $f2 #This displays the title of each product (just for testing)
done
$f2
이제 각 헤더( )를 다른 파일( $csv2
)과 비교하여 일치하는 항목이 있는지 확인하고 싶습니다 .
CSV2:
$1.99,The Power of Now,www.dvd.com,45674
$9.99,Titan the Power,www.otherwebsite.com,13357
$2.99,The incredible Hulk,www.purchase.com,13956
나는 파일을 다음과 같이 비교할 수 있다는 것을 알고 있습니다.
if [ "$f2" == "$csv2" ]; then
echo "match"
fi
위의 코드는 전체 내용과 일치하며, 안의 줄은 csv2
순서가 다를 수 있으며 관심 없는 다른 내용이 포함될 수 있습니다. 스크립트 $f2
에서 .NET 파일의 헤더와 일치하는 행만 알려주기를 원합니다 csv2
. 따라서 첫 번째 헤더만 에 있는 경우 출력은 다음과 같을 수 있습니다 csv2
.
Matching lines:
$9.99,Titan the Power,www.otherwebsite.com,13357
$9.99,Titan the Power,www.example.com,565654
위와 같이 비교할 수 있도록 원래 행과 일치하는 행을 출력으로 표시하고 싶습니다(다른 필드 값 간에는 약간의 차이가 있지만 $input
헤더 $csv2
는 동일합니다).
답변1
나는 다음과 같은 첫 번째 파일에서 모든 헤더를 얻을 것입니다
interesting_titles=$(cat $input |cut -d, -f2)
그런 다음 이것을 사용하여 두 번째 파일에서 이러한 헤더를 검색합니다.
grep -F "$interesting_titles" $csv2
grep이 반환한 모든 항목은 일치합니다.
한 줄로 단축할 수 있습니다.
grep -F "$(cat $input |cut -d, -f2)" $csv2
두 개의 파일을 나란히 출력하려면 다음과 같은 for 루프가 필요할 수 있습니다.
cat $input |cut -d, -f2 | while read t; do
grep -i "$t" $csv2
if [ $? -eq 0 ];then
grep -i "$t" $input
fi
done
$input의 각 행을 반복하고 $input의 $csv2에 있는 레코드를 확인하고 인쇄합니다.