So geben Sie Spalten mit speziellen Mustern aus

So geben Sie Spalten mit speziellen Mustern aus

Ich habe eine Spalte mit einigen Worten:

scatman
batman
superman
scatman
scatman
batman
superman
scatman
scatman
batman
superman
scatman
batman
WWWWWWWW
superman
scatman
batman
superman
scatman

Ich sollte einige Muster erstellen, bei denen ich Wort für Wort drei Wörter brauche: Scatman, Batman, Superman. Wo ich wiederholte Wörter habe, wie Scatman & Scatman in Zeile 4 & 5 oder wo ich andere Wörter habe, sollte ich sie streichen. Ich habe geschrieben:

grep "scatman\|batman\|superman" file

Ok, ich habe das Wort WWWWWWWW abgelehnt, aber ich verstehe nicht, wie ich meine Spalte Wort für Wort anzeigen kann. Als Ergebnis habe ich:

scatman
batman
superman
scatman
scatman
batman
superman
scatman
scatman
batman
superman
scatman
batman
superman
scatman
batman
superman
scatman

In Zeile 4 und 5 habe ich Wortwiederholungen, aber das gefällt mir nicht. Wo ist der Fehler?

Antwort1

Dies wird genau das tun, was Sie wollen

#!/bin/bash
array=(
[0]="scatman"
[1]="batman"
[2]="superman"
)
count=0
while read line; do
    for i in "${array[@]}";
    do
    if [[ $count == 3  ]]; then
    count=0
    fi
    if [[ $line == ${array[$count]} ]]; then
    #echo "$line"
    printf "%s " $line

    # uncomment if you want every word on a new line
    #echo "$line" >> newfile.txt # each word on a line
    #or
    # uncomment if you want all will be on one line
    #printf "%s " $line >> newfile.txt

    count=$((count+1))
    else
    continue
    fi

    done

done < file.txt #this is your original file

Druckt jedes Wort in einer neuen Zeile aus, wie folgt:

scatman
batman
superman
scatman
batman
superman
scatman
batman
superman
scatman
batman
superman
scatman
batman
superman
scatman

oder in einer Zeile wie dieser:

scatman batman superman scatman batman superman scatman batman superman scatman batman superman scatman batman superman scatman

Antwort2

grepDies ist mit und möglich awk:

cat words.txt |
grep -E 'scatman|batman|superman' |
awk '{
      last_word = cur_word
      cur_word = $0
      if (cur_word == last_word)
        next
      else
        print $0
      }' < word.list 

Dies ermöglicht einen erweiterten regulären Ausdruck, den Sie als Suchziel grep -Everwenden können . Der Code sucht nach wiederholten Wörtern und überspringt diese.|orawk

Sie können dies alles in einer Zeile tun, wenn Sie möchten:

cat words.txt | grep -E 'scatman|batman|superman' | awk '{ last_word = cur_word; cur_word = $0; if (cur_word == last_word) next; else print $0 }' < word.list`

Antwort3

etwas greifen

In Zeile 4 und 5 habe ich Wiederholungen, aber das gefällt mir nicht

um wiederholte Zeilen wegzulassen: fügen Sie | uniqam Ende Ihres Befehls hinzu

verwandte Informationen