n보다 긴 줄을 한 줄로 축소하고 해당 줄의 다른 인스턴스는 그대로 유지합니다.

n보다 긴 줄을 한 줄로 축소하고 해당 줄의 다른 인스턴스는 그대로 유지합니다.

다음 형식의 도메인 이름 파일이 있습니다.

www.mozilla.org
www.mozilla.org
www.mozilla.org
www.mozilla.org
www.google.com
www.google.com
www.rust-lang.org
www.google.com
www.google.com
www.google.com
www.google.com

예를 들어 런타임이 4보다 길면 동일한 행의 실행을 축소하고 싶습니다. 그러면 다음과 같은 출력 데이터가 제공됩니다.

www.mozilla.org
www.google.com
www.google.com
www.rust-lang.org
www.google.com

나는 Bash에서 이 작업을 수행하기를 바라고 있으며, 내가 얻은 가장 가까운 방법은 Python에서 다음과 같은 간단한 5분 솔루션입니다.

inp = """www.mozilla.org
www.mozilla.org
www.mozilla.org
www.mozilla.org
www.google.com
www.google.com
www.rust-lang.org
www.google.com
www.google.com
www.google.com
www.google.com"""

def collapse(n, inp):
    prev = ""
    output = []
    cnt = 0
    for line in inp.split('\n'):
        if line == prev:
            cnt += 1
        if line != prev:
            if cnt >= n-1:
                output = output[:-cnt]
            cnt = 0
        prev = line
        output.append(line)
    #last set of lines is an edgecase
    if cnt > n-2:
        output = output[:-cnt]

    print('\n'.join(output))
            

collapse(4, inp)

답변1

uniq -c실행 길이를 계산한 다음 awk해당 횟수에 따라 적절한 횟수만큼 데이터를 출력하는 데 사용됩니다 .

$ uniq -c file | awk '$1 >= 4 { $1 = 1 } { for (i = 1; i <= $1; ++i) print $2 }'
www.mozilla.org
www.google.com
www.google.com
www.rust-lang.org
www.google.com

uniq -c명령은 샘플 데이터를 사용하여 다음 줄을 출력합니다.

   4 www.mozilla.org
   2 www.google.com
   1 www.rust-lang.org
   4 www.google.com

awk명령은 첫 번째 열의 숫자에 대해 작동하며, 숫자가 4보다 작으면 두 번째 열의 값을 출력하고, 그렇지 않으면 한 번 출력합니다.

관련 정보