쉘 스크립트에서 awk에 값 전달

쉘 스크립트에서 awk에 값 전달

그래서 파일에서 읽은 IP 묶음인 대상 배열이 있습니다. 이제 내 IP와 ssh 명령의 결과가 포함된 파일을 분류하려고 합니다. 하지만 각각에 대해 3개의 다른 비밀번호를 시도하고 있기 때문입니다. target 을 입력하면 2개의 거부와 1개의 작업 예약 결과를 받게 됩니다. 그래서 저는 작업이 특정 결과에 대해 예약되어 있는지 확인한 다음 "$ip OK"를 인쇄하고 그렇지 않은 경우 "$ip failed"를 인쇄할 것이라고 생각했습니다. 이것이 제가 가진 것입니다.

#!/bin/bash
for ip in "${targets_array[@]}"
do
   cat "$output_file" | awk -v ip="$ip" '/$ip/&&/job/ {result="OK"} END {
     !result?result="failed":result=result;}'

done
내가 하고 싶은 일의 의사코드:
1. 필요한 IP와 "job"이라는 단어를 찾을 수 있는 파일의 cat 출력 파일 라인
2.1. 발견되면 문자열 변수에 "$ip OK"가 추가되어 인쇄됩니다.
2.2 찾을 수 없는 경우 문자열 변수 "$ip failed"에 추가합니다.
3. 변수에 저장된 결과로 출력 파일을 덮어씁니다.

그러나 디버그 모드에서 실행하면 값이 awk 스크립트에 전달되지 않는 것을 볼 수 있습니다. 어떻게 통과할 수 있나요?

+ awk -v ip= '/$ip/&&/job/ {result="OK"} END {
     !result?result="failed":result=result;}'

내가 자르고 있는 파일:

unwantedString 124.131.8010 Permission denied, please try again.
unwantedString 125.124.90.134 Permission denied, please try again.
unwantedString 145.120.100.8 Permission denied, please try again.
unwantedString 145.101.100.158 Permission denied, please try again.
unwantedString 124.131.80.2 Permission denied, please try again.
unwantedString 125.124.90.134 job 32 at 2020-12-16 23:30
unwantedString 145.120.100.8 Permission denied, please try again.
unwantedString 145.101.100.158 job 27 at 2020-12-16 23:30
unwantedString 124.131.8010 Permission denied, please try again.
unwantedString 125.124.90.134 Permission denied, please try again.
unwantedString 145.120.100.8 Permission denied, please try again.
unwantedString 145.101.100.158 Permission denied, please try again.

답변1

먼저 오류가 있습니다: !#/bin/bash #!/bin/bash.

그렇다면 ip=$ip이어야 합니다 ip="$ip".

그런 다음 변수를 사용하려면 달러 기호 없이 변수를 호출할 수 있지만 ip호출해야 하는 패턴 영역 내에서는 호출할 수 없습니다 $0 ~ ip.

귀하의 출력에 따라 :

#!/bin/bash
for ip in "${targets_array[@]}" 
do
ip="$ip"
awk -v ip="$ip" '{if ( $2 == ip && $3 == "job" )  {print $2 " success"} else {print $2 " failed"}}' output_file > out
done

관련 정보