Home > Enterprise >  Bash renaming with For Loop
Bash renaming with For Loop

Time:10-13

I have files name filename.gz.1 and i need to rename them to filename.gz, There are allot of files and every name is different,

I know i cant to this for i in $(ls); do mv $i $i.1; done, But can i do this reverse, from filename.gz.1 to filename.gz and keep the original file name?

I have tried this,

for i in $(ls | grep "xz\|gz"); do echo "mv $i $i | $(rev) | $(cut -c3-) | $(rev) |)"; done

But this ignores my Pipes.

Can anyone help me?

CodePudding user response:

You can use

for i in ...;
do
    echo "$i --> ${i%.*}"
done

The ${i%.*} will remove at the end (%) what match a period followed by anything (.*)

CodePudding user response:

You have to use --extended-regexp when using a pipe as separation.

echo -e "foo.xz\nbar.gz\nbaz" | grep -E "(xz|gz)"

and don't use ls for list your files, it is not save. instead you can use a loop to search for files.

for file in /PATH/TO/FILES; do
echo $file
done

I would also recommend to use regex to search for filenames ending with a number, like ...

if [[ $file =~ [[:digit:]]$ ]]; then
  echo ${file%.*}
fi

CodePudding user response:

I was able to resolve it like this:

for i in $(ls | grep "xz\|gz"); do echo "mv $i $i" | rev | cut -c3- | rev; done | bash
  • Related