여러 구분 기호를 사용하여 문자열 분할

여러 구분 기호를 사용하여 문자열 분할

다음 문자열이 포함된 텍스트 파일이 있는데 이를 CSV 파일로 변환하고 싶습니다.

다음 문자열을 분할하고 싶습니다.

location = /example/url/newsite/redirect {return 301 https://example.com/fr;}

...다음 값으로:

/example/url/newsite/redirect,301,https://example.com/fr

현재 다음 명령을 사용하고 있습니다

awk '{gsub(/;}/,"",$6); if ($1 == location) print $3","$6 }' redirections/*.redirections >> redirect-csv/redirect.csv

이상적으로는 파일 이름을 지정할 필요가 없습니다. Redirections/의 모든 *.redirections 파일을 가져와야 하며 1:1 매핑을 수행하여 Redirect-csv에 파일을 생성해야 합니다.

redirections/
site1.redirections
site2.redirections

Run the magic command.

redirect-csv/
site1.csv
site2.csv

답변1

이런 종류의 문제를 해결하는 가장 좋은 방법은 정규식을 사용하여 문자열을 패턴과 일치시키고 관련 부분을 추출하는 것입니다.

echo "location = /example/url/newsite/redirect {return 301 https://example.com/fr;}" |
  sed -n 's/^location = \(.*\) {return \(3[[:digit:]]\{2\}\) \(.*\);}$/\1,\2,\3/p'

주어진

/example/url/newsite/redirect,301,https://example.com/fr

또는 필드에 CSV 형식의 특수 문자(예 ,: , ")가 포함될 수 있는 경우:

perl -MText::CSV -lne '
  BEGIN{$c = Text::CSV->new}
  if (/^location = (.*) \{return (3\d\d) (.*);\}$/) {
    $c->print(STDOUT, [$1, $2, $3])
  }'

답변2

이를 변경한 후 첫 번째 솔루션을 기반으로 한 솔루션이 있습니다.

for file in redirections/*.redirection; do fname=$(basename $file); awk '{gsub(/;}/,"",$6); print $3" & "$5" & "$6 }' $file > redirect-csv/${fname/.redirection/.csv}; done

답변3

음, 이 선이 항상 같은 모델을 따른다면, 또 다른 선이 있을까요?

echo "location = /example/url/newsite/redirect {return 301 https://example.com/fr;}" | awk '{gsub(/;}/,"",$6); print $3" & "$5" & "$6 }'

"myfile.csv"로 리디렉션하세요.

awk '{gsub(/;}/,"",$6); print $3" & "$5" & "$6 }' list.txt >> myfile.csv

list.txt에 해당 줄이 포함되어 있는 경우

답변4

  1. 실수 - 이 코드는 OP 질문의 약어입니다.

    awk '...stuff...' r/*.red >> r-c/red.csv
    

    ...많은 파일을 입력하고 변경한 다음 매우 긴 파일 하나를 출력합니다. 빨간색.csv문서. >>리디렉션동작은 매우 유사합니다 cat foo/* > bar/baz.

  2. 동일한 약어를 사용하여 단어 줄 바꿈을 방지하고, with basename 및 xargs를 사용하고, cp이름을 변경할 때 r/파일을 복사 하는 명령을 생성하고 r-c/, 다음을 사용하여 해당 새 파일을 그 자리에서 편집합니다.암소 비슷한 일종의 영양 sed:

    basename -a -s r/*.red | xargs -L 1 -I {}   cp  r/{}.red  r-c/{}.csv
    sed -i 's/^[^=]*= \|\;}$//g;s/ [^ ]* /,/;s/ /,/'  r-c/*.csv
    

관련 정보