TransWikia.com

how to grep both files , but exclude other files

Unix & Linux Asked on October 31, 2021

We want to search string by grep to both files:

The files are

/confluent/logs/server.log
/confluent/logs/server.log.1

But we not want to match the other files as

/confluent/logs/server.log.2
/confluent/logs/server.log.3 

etc

So instead to do double grep as

grep log.retention.bytes  /confluent/logs/server.log
grep log.retention.bytes  /confluent/logs/server.log.1

we want to find the match of log.retention.bytes on both files on the same time

we try to do

grep log.retention.bytes   /opt/mcspace/confluent/logs/server.log.*[1]

but this is wrong

2 Answers

The simplest way to grep in two files, is to give both files to grep:

grep log.retention.bytes /confluent/logs/server.log /confluent/logs/server.log.1

When you have more files, you can either list them all manually or use a glob that matches only your specific files. For example, in bash:

shopt -s extglob
grep log.retention.bytes /confluent/logs/server.log?(.1)

Finally, and probably most simple in your case, you can use brace expansion as shown in Tomassz's answer.

Answered by terdon on October 31, 2021

grep log.retention.bytes server.log{,.1}

In order to keep log entries (appended) in chronological order, you might want to reverse the order of files:

grep log.retention.bytes server.log{.1,}

which is of course equivalent to:

grep log.retention.bytes server.log.1 server.log

as the brace expansion is done by the shell before executing the grep command.

Moreover, with zsh shell you can easily automatically glob for the last N files matching a pattern with:

grep log.retention.bytes server.log*(Om[-2,-1])

where Om means order by mtime descending and [-2,-1] fetches 2 last rows. This trick is worth remembering if you watch to search more files and do not want to type them manually.

Answered by Tomasz Pala on October 31, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP