Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove one level of file extension from filename in shell script

Tags:

bash

shell

unix

ksh

I have a Bash script that loops through files and masks them. The files are gzipped and I need to gunzip them first before passing them as argument to a Python program as shown in script below. The problem is that variable $i does not turn into the unzipped version of the filename. The file name before unzipping is my-log-1.c.log.gz. After running gunzip on the file as below I want to pass my-log-1.c.log as the argument to the masker.sh script, not the .gz version. How would I do this?

#!bin/bash

cd /home/logs

  for i in *
     gunzip $i
     do
       python masker.py $i  # python program masks files 
     rm $i
     echo "masked_file and removed =  $i"
   done
like image 427
user836087 Avatar asked Feb 03 '26 22:02

user836087


1 Answers

Using basename:

for i in; do
  gunzip "$i"
  i=$(basename "$i" .gz)
  python masker.py "$i"  # python program masks files 
  rm $i
  echo "masked_file and removed =  $i"
done

The first argument is the filename and the second one is the extension you want to remove.

like image 133
perreal Avatar answered Feb 06 '26 13:02

perreal