Shell / 쉘 스크립트 질문

zxerp의 이미지

이제막 쉘 입문한 초보입니다.
출력 관련 질문 확인 부탁드립니다.

외부에서 데이터를 텍스트파일로 아래와 같은 형식으로 받아오고있습니다.

----txt파일----
1번서버
item1
item2
item3
item4
2번서버
item1
item2
item3
item4
----------------

현재는 서버가 2대 뿐이라
제 지식수준에서 간단한 sed 명령어로 한줄씩읽고 변수등록하여
간단하게 정렬 후 출력하고있습니다.

예시)
#!/bin/bash

item1= `sed -n 1p /home/txt`
item2= `sed -n 2p /home/txt`
item3= `sed -n 3p /home/txt`

./script $item1 >> 1.txt
./script $item2 >> 1.txt
./script $item3 >> 1.txt

후에 서버갯수나 아이템갯수가 늘어났을때 어떡해야할지 방법을 찾고있습니다.

----txt파일----
1번서버
item1
item2
item3
item4

2번서버
item1
item2
item3
.
.
N번서버
item1
item2
.
.
.
item23
----------------

(서버별로 나누어
N번서버 item값 변수등록 -> 출력 )

고수분들 도움 부탁드립니다.

chanik의 이미지

이런 식으로 하시면 되지 않을까요?

$ cat test.bash
#!/bin/bash
while read line; do
  if [[ $line =~ ^([0-9]+)번서버$ ]]; then
    ofile=${BASH_REMATCH[1]}.txt
    echo set output file as $ofile
  elif [[ $line != "" ]]; then
    ./script $line >> $ofile
  fi
done

$ ./test.bash < txt
set output file as 1.txt
set output file as 2.txt
  .
  .
zxerp의 이미지

답변 감사합니다!

혹시 ./script $line >> $ofile 이부분에서
아래와 같은 오류가 출력되는데
$file: ambiguous redirect

간략한 설명 가능하실까요?

chanik의 이미지

./script $line >> $ofile 부분은 이해를 돕기 위해 질문글에 올리신걸 따서 쓴 것이고, 제 환경에는 ./script 라는 스크립트는 존재하지 않습니다. 막무가내로 실행하면 아래와 같이 나옵니다. 말씀하신 오류와는 좀 다른 결과가 나오죠.

$ ./test.bash < txt
set output file as 1.txt
./test.bash: line 7: ./script: No such file or directory
./test.bash: line 7: ./script: No such file or directory
./test.bash: line 7: ./script: No such file or directory
./test.bash: line 7: ./script: No such file or directory
set output file as 2.txt
./test.bash: line 7: ./script: No such file or directory
./test.bash: line 7: ./script: No such file or directory
./test.bash: line 7: ./script: No such file or directory
./test.bash: line 7: ./script: No such file or directory

그리고, 오류를 일으키는 부분을 echo $line >> $ofile 정도로 바꿔서 실행해보면 아래와 같이 잘 동작합니다.

#!/bin/bash
while read line; do
  if [[ $line =~ ^([0-9]+)번서버$ ]]; then
    ofile=${BASH_REMATCH[1]}.txt
    echo set output file as $ofile
  elif [[ $line != "" ]]; then
    echo $line >> $ofile
    #./script $line >> $ofile
  fi
done

$ cat txt
1번서버
item1
item2
item3
item4
 
2번서버
item1
item2
item3
item4
$ ./test.bash < txt
set output file as 1.txt
set output file as 2.txt
$ cat 1.txt
item1
item2
item3
item4
$ cat 2.txt
item1
item2
item3
item4

제 환경에서는 오류가 재현되지 않으므로 설명은 어렵네요. 혹시 오류 재현되는 스크립트와 샘플데이터를 올려주실 수 있는지요?

chanik의 이미지

다시 읽어보니 $ofile 을 $file 이라고 잘못쓰신 것 같군요

익명 사용자의 이미지

$file은 댓글에 제가 쓰다가 낸 오타입니다.

스크립트파일은 해당값을 막대 그래프및 %로 출력 처리하는 스크립트인데 이게
서버이름의 공백을 인식못해서 문제가 발생한거였네요

+) bash rematch 란걸 처음 알게되었는데 상당히 유용하네요

친절한 답변 감사합니다!