2017-03-28 5 views
2

에서 파일을 읽을 어떻게 라텍스 파일 마녀의 무리 사용을 가진 \input{filename.tex} 매크로 (그것이 #include에서 C처럼 작동), 나는 내가 출력 할 수있는 하나의에 그들 모두를 해결하려면 .tex 파일 (파일은 \input{} 매크로에 붙여 넣어야합니다. 각 파일을 한 번만 참조한다고 가정하는 것이 안전합니다).반복적으로 AWK

예 :

tesis.tex :

My thesis. 
\input{chapter1.tex} 
More things 
\input{chapter2.tex} 

chapter1.tex :

Chapter 1 content. 

chapter2.tex :

Chapter 2 content. 
\include{section2-2.tex} 

section2-2.tex :

Section 1. 

원하는 결과가 있어야한다 :

My thesis. 
Chapter 1 content. 
More things 
Chapter 2 content. 
Section 1. 

나는이 AWK 프로그램으로이 문제를 해결 할 수있을 것입니다 만 \input{foo.tex} 수준 있었다면 :

/\\input\{.*\}/{ 
    sub(/^[^{]*{/,"",$0) 
    sub(/}[^}]*$/,"",$0) 
    system("cat " $0) 
    next 
} 

{ 
    print $0 
} 

어떤 방식이 있는가 AWK에서 재귀 적으로 파일을 읽으시겠습니까?

감사합니다 (I는 다른 언어와 함께 할 열려입니다,하지만 POSIX는 더 나은 동부 표준시)! 당신은 또한 bash는 그것을 태그를 가지고 있기 때문에

답변

2

다음은 작업에 대한 재귀 함수에서 getline을 사용하는 awk의 솔루션입니다. 나는 chapter2.tex 가정 :

Chapter 2 content. 
\input{section2-2.tex} 

코드 :

$ cat program.awk 
function recurse(file) {    # the recursive function definition 
    while((getline line<file) >0) { # read parameter given file line by line 
     if(line~/^\\input/) {   # if line starts with \input 
      gsub(/^.*{|}.*$/,"",line) # read the filename from inside {} 
#   print "FILE: " line  # debug 
      recurse(line)    # make the recursive function call 
     } 
     else print line    # print records without \input 
    } 
    close(file)      # after file processed close it 
} 
{          # main program used to just call recurse() 
    recurse(FILENAME)     # called 
    exit        # once called, exit 
} 

실행이 :

$ awk -f program.awk tesis.tex 
My thesis. 
Chapter 1 content. 
More things 
Chapter 2 content. 
Section 1. 

솔루션 \input 그것에 다른 데이터없이 기록의 시작 부분에있을 것으로 예상하고있다.

+1

고마워요! 이것은 내 문제를 완벽하게 해결하고 쉽게 확장 할 수 있습니다. –

+1

awk에서 구현 된 my bash 솔루션과 비슷합니다. awk이 함수 자체를 호출 할 수 있다는 것을 나는 몰랐다. 멋지다. –

0

,이 같은 배쉬에서 작동 할 수 있지만 테스트되지 않은 상태입니다 : bash는 4.4에서

#!/bin/bash 
function texextract { 
while read -r line;do  
    if [[ "$line" =~ "input" || "$line" =~ "include" ]];then #regex may need finetune 
     filename="${line: 0:-1}" #removes the last } from \include{section2-2.tex} 
     filename="${filename##*{}" #removes from start up to { ---> filename=section2-2.tex 
     texextract "$filename" #call itself with new args 
    else 
     echo "$line" >>commonbigfile 
    fi 
done <"$1" #$1 holds the filename send by caller 
return 
} 

texextract tesis.tex #masterfile 

(그리고 아마도 다른 버전도) 함수는 자신을 호출 할 수 있습니다. 이것은 내가 여기서 사용하는 것입니다.