3

So I have put a load of names of files in a text file, these are specifically .log files:

ls *.log > finished_data.txt

Now that I Have the list of .log files, how do I keep the names but remove the .log extension? My thought process is renaming them all?

user3667111
  • 611
  • 6
  • 21

2 Answers2

7

Just loop through the .log files and move them:

for file in *.log
do
    mv "$file" "${file%.log}"
done

This uses shell parameter expansion:

$ d="a.log.log"
$ echo "${d%.log}"
a.log
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • Thank you, works perfectly how could I reverse the action? say adding the .log on the end to certain files? – user3667111 Jun 21 '16 at 13:17
  • 1
    @user3667111 just say `mv "$file" "${file}.log"`. – fedorqui Jun 21 '16 at 13:20
  • @gniourf_gniourf oh thanks, I always get confused with `%` and `%%`. I see `%` strips the shortest match, which is most accurate. Regarding the syntax of the `for` loop: is there any difference? – fedorqui Jun 21 '16 at 13:25
  • 1
    @gniourf_gniourf ah true! I misunderstood your comment and thought you referred to using `for file in ...; do` instead of `for file in ...` + new line + `do`. You are absolutely right, updating. – fedorqui Jun 21 '16 at 13:30
1

Using rename to rename all .log files by removing .log from the end:

rename 's/\.log$//' *.log
  • \.log$ matches .log at the end of the file name and it is being omitted by replacing with blank

If you are using prename, then you can do a dry-run first:

rename -n 's/\.log$//' *.log

If satisfied with the changes to be made:

rename 's/\.log$//' *.log
heemayl
  • 39,294
  • 7
  • 70
  • 76