Counting words and delete strings from a text file in unix
I have a question for you: I have a big log file and I want to clean it. I'm interested only in strings which contain determinate word and I want to delete t开发者_如何学Che other strings. i.e.:
access ok from place1
access ko from place1
access ok from place2
access ko from place2
access ok from place3
access ko from place3
......
And I want to obtain only the 'place2' entry:
access ok from place2
access ko from place2
How can I do it? Thanks in advance!
grep "place2" /path/to/log/file > cleanedFile.txt
I wrote a blog post about combining find/sed/grep - you might be interested.
Try this grep command:
grep "\<place2\>" log-file > out-file
\<
and \>
will make sure to match full word thus inplace2 will NOT be matched.
grep "\<place2\>" file.log > file.out
wc file.out
wc (word count) for counting the words. But for 2 questions, you should normally open two questions. :)
Another take, select lines where the 4th column equals "place2"
awk '$4 == "place2"' file
Unlike most other answers, this modifies the file in-place and does not need further renaming.
sed -i -n '/place2/p' /var/log/file
This assumes GNU sed. If you don't have GNU sed but have perl:
perl -i -ne '/place2/ && print' /var/log/file
These 2 examples does in-place editing as well.
$ awk '$NF=="place2"{print $0>FILENAME}' file
$ ruby -i.bak -ane 'print if $F[-1]=="place2"' file
There are other ways to files these lines
sed -i.bak -n '/place2$/p' file
grep 'place2$' file > temp && mv temp file
Purely using the shell
while read -r line; do case $line in *place2) echo "$line";; esac; done < file > temp && mv temp file
精彩评论