Rename file based on zgrep results

I have multiple gz files testfile1.gz, testfile2.gz, etc. I am trying to zgrep each file and redirect the output to another file with the same filename but no extension. Below is what I am trying, but I would rather be testfile1, testfile2, etc. No gz extension. How should I do it? Thank.

for file in hello*; do zgrep 'line' $file > $file.TEST ; done

      

+3


source to share


2 answers


You may try:

for file in hello*.gz; do
    zgrep 'line' > "${file%.gz}.TEST"
done

      



From TLDP on Row Manipulation :

$ {string% substring} # Removes the shortest match $ substring from $ string.

+2


source


The team basename

is your friend:

for file in hello*; do zgrep 'line' "$file" > $(basename "$file" .gz); done



Alternatively, just remove the '.gz' from the output filename:

for file in hello*; do zgrep 'line' "$file" > $(sed 's/.gz//' <<< "$file"); done

+1


source







All Articles