Vivek S
Vivek S

Reputation: 53

How to extract file name after grepping a string in unix

I am using the code below to grep some string:

grep 'string' *.log | grep -v 'string1'

I am getting output in particular file. My requirement is to extract that file name to a variable. How I can do that effectively?

Upvotes: 0

Views: 1099

Answers (2)

Ravi Bhushan
Ravi Bhushan

Reputation: 253

use command

basename "filePath" "fileExtension"

ex: basename /home/john/xyz.txt .txt

output: xyz

Upvotes: 0

John1024
John1024

Reputation: 113834

In general, you can capture the output of any command into a shell variable via command substitution like this:

variable=$(command arg1 arg2)

This is appropriate for your particular case if you are sure that there will be only one file name produced by the grep pipeline. In that case, you capture its name into shell variable fname via:

fname=$(grep -lZ string *.log | xargs -0 grep -lv string1)

This is safe for difficult file names because, via the -Z and -0 options, we use NUL-separated lists. The -l option to grep is useful here because it suppresses the normal grep output and just prints the file names.

If there might be multiple file matches, then, if you can use an advanced shell like bash, try:

grep -lZ string *.log | xargs -0 grep -lvZ string1 | while IFS= read -r -d $'\0' fname
do
    # Process file "$fname"
done

This is also safe for difficult file names because, throughout the pipeline, it uses NUL-separated lists.

For a POSIX shell, read works with newline-separated input. To make the above safe for difficult file names, the -d option is used which is supported by bash, zsh, and other advanced shells.

Upvotes: 2

Related Questions