1

[root@localhost ~]# ls *.bak

test2.bak test3.bak test9.bak test.bak test.txt.bak

How to drop all .bak in all file?This is my current try

ls *.bak|xargs -t -i mv {}.bak {}

But it don't work for me.Is there any workaround here?

5 Answers 5

2

A loop should do (in a POSIX-like shell):

for f in *.bak; do 
    mv -- "$f" "${f%.*}"
done

And as one line:

for f in *.bak; do mv -- "$f" "${f%.*}"; done
1

Use rename command:

rename 's/\.bak$//' *.bak

  • 's/\.bak$//' - perl expression to match all filenames ending with .bak and strip the extension
4
  • I don't know why it don't work for me. Commented Jun 23, 2017 at 14:11
  • @yode, try prename 's/\.bak$//' *.bak (Perl version) Commented Jun 23, 2017 at 14:17
  • It's seem rename .bak '' *.bak work for this.. Commented Jun 23, 2017 at 14:23
  • it seems that you are using another implementation, see this post unix.stackexchange.com/questions/78621/… Commented Jun 23, 2017 at 14:25
0

Something that should work across all platforms:

for i in *.bak
do
  mv $i `echo $i | sed 's/\.bak$//'`
done
1
  • You need quotes around $i and the command substitution to deal with whitespace in filenames. (Some newlines would still cause somewhat odd results.) Commented Jun 23, 2017 at 15:23
0

As the promp of RomanPerekhrest's answer here,I find this command work for me.

rename .bak '' *.bak
1
  • Note that it would rename best.baker.bak to bester.bak and would choke on file names that start with -. Commented Jun 23, 2017 at 14:35
-1
#!/bin/bash
for val in \`ls *.bat`
do
    mv $val `echo $val | cut -f1 -d'.'`
done
2
  • That makes a lot of assumptions, like that none of the bat files are of type directory, that their names don't contain space, tab, newline, *, ?, [ backslash characters, that they don't start with -, that they contain no other . characters. Commented Jun 23, 2017 at 14:39
  • The ls here doesn't do anything (but cause issues), the shell still generates the list of file names. See also: mywiki.wooledge.org/BashPitfalls#for_i_in_.24.28ls_.2A.mp3.29 Commented Jun 23, 2017 at 15:25

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.