텍스트 파일의 미리 정의된 모든 단어에 증분 개수를 추가하려면 어떻게 해야 합니까?

텍스트 파일의 미리 정의된 모든 단어에 증분 개수를 추가하려면 어떻게 해야 합니까?

텍스트 파일의 미리 정의된 모든 단어에 증분 개수를 추가하려면 어떻게 해야 합니까?

이 질문과 같습니다. 텍스트 파일의 모든 줄에 증분 개수를 추가하려면 어떻게 해야 합니까?

텍스트 파일에 증분 개수를 추가하고 싶습니다. 하지만 각 줄에 증분 개수를 추가하는 대신 미리 정의된 단어에 증분 개수를 추가하고 싶습니다.

예를 들어, 텍스트에서 'cinema'라는 단어를 세고 싶다면 모든 'cinema'를 'cinemaN'으로 변경하고 싶습니다. 여기서 N은 증분 숫자이고 N의 최대값은 얼마나 많은지에 따라 달라집니다. 본문에 '영화'라는 단어가 여러 번 등장합니다.

따라서 다음 텍스트를 포함하는 입력 텍스트 파일은 다음과 같습니다.

그는 영화관으로 차를 몰고 갔다. 이후 그는 표를 구매하기 위해 영화관 안으로 들어갔고, 나중에 알고 보니 마지막으로 영화관을 방문한 지 2년이 넘었다.

다음 내용으로 출력 파일을 생성합니다.

그는 영화관으로 차를 몰고 갔다. 그 후 그는 티켓을 구매하기 위해 시네마2 안으로 들어갔고, 나중에 시네마3를 마지막으로 방문한 지 2년이 넘었다는 것을 알게 되었습니다.

바람직하게는 선택한 단어에 역순으로 번호를 매길 수 있기를 바랍니다.

즉, 다음 내용으로 두 번째 출력 파일이 생성됩니다.

그는 영화관으로 차를 몰고 갔다3. 그 후 그는 티켓을 구매하기 위해 시네마2 안으로 들어갔고, 나중에 시네마1을 마지막으로 방문한 지 2년이 넘었다는 것을 알게 되었습니다.

답변1

나는 perl이것을 선호합니다 :

$ cat ip.txt 
He drove his car to the cinema. He then went inside the cinema to purchase tickets, and afterwards discovered that it was more then two years since he last visited the cinema.

$ # forward counting is easy
$ perl -pe 's/\bcinema\b/$&.++$i/ge' ip.txt 
He drove his car to the cinema1. He then went inside the cinema2 to purchase tickets, and afterwards discovered that it was more then two years since he last visited the cinema3.
  • \bcinema\b검색할 단어, 다른 단어의 일부와 일치하지 않도록 단어 경계를 사용합니다. 예를 들어, \bpar\b일치하지 않습니다 apartor park또는spar
  • ge플래그 g는 전역 교체용입니다. e교체 섹션에서 Perl 코드를 사용할 수 있습니다.
  • $&.++$i$i일치하는 단어와 기본값이 다음과 같이 미리 증가된 값을 연결한 것입니다.0


반대로, 먼저 카운트를 얻어야 합니다...

$ c=$(grep -ow 'cinema' ip.txt | wc -l) perl -pe 's/\bcinema\b/$&.$ENV{c}--/ge' ip.txt 
He drove his car to the cinema3. He then went inside the cinema2 to purchase tickets, and afterwards discovered that it was more then two years since he last visited the cinema1.
  • c해시를 통해 액세스할 수 있는 환경 변수가 됩니다.%ENV

또는 perl혼자서 파일 전체를 후루룩 마시고

perl -0777 -pe '$c=()=/\bcinema\b/g; s//$&.$c--/ge' ip.txt 

답변2

다중 문자 RS용 GNU awk를 사용하면 대소문자를 구분하지 않고 단어 경계를 구분합니다.

$ awk -v RS='^$' -v ORS= -v word='cinema' '
    BEGIN { IGNORECASE=1 }
    { cnt=gsub("\\<"word"\\>","&"); while (sub("\\<"word"\\>","&"cnt--)); print }
' file
He drove his car to the cinema3. He then went inside the cinema2 to purchase tickets, and afterwards discovered that it was more then two years since he last visited the cinema1.

답변3

단어 뒤의 구두점을 고려합니다.
앞으로 번호 매기기:

word="cinema"
awk -v word="$word" '
    { 
      for (i = 1; i <= NF; i++) 
        if ($i ~ word "([,.;:)]|$)") { 
          gsub(word, word "" ++count,$i) 
        }
      print 
    }' input-file

역방향 번호 매기기:

word="cinema"
count="$(awk -v word="$word" '
    { count += gsub(word, "") }
    END { print count }' input-file)"
awk -v word="$word" -v count="$count" '
    { 
      for (i = 1; i <= NF; i++) 
        if ($i ~ word "([,.;:)]|$)") { 
          gsub(word, word "" count--, $i) 
        }
      print 
    }' input-file

답변4

단어에 내림차순으로 태그를 지정하려면 정규 표현식을 반전하고 데이터를 반전시킨 다음 마지막으로 날짜를 다시 한 번 반전시켜 변환을 수행합니다.

perl -l -0777pe '$_ = reverse reverse =~ s/(?=\bamenic\b)/++$a/gre' input.data

결과

He drove his car to the cinema3. He then went inside the cinema2 to purchase tickets, and
afterwards discovered that it was more then two years since he last visited the cinema1.

단어에 오름차순으로 태그를 지정하기 위해 단어에 대한 뒤돌아 검색을 수행합니다.

perl -lpe 's/\bcinema\b\K/++$a/eg' input.data

결과

He drove his car to the cinema1. He then went inside the cinema2 to purchase tickets, and
afterwards discovered that it was more then two years since he last visited the cinema3.

관련 정보