0

I have a file name such as follows:

file_name1.pdf.sometext.here

I have a directory of several files in the same format, and I want to edit all the files so that the portion after .pdf is deleted... thus the file would look like this

file_name1.pdf
sinclair
  • 2,812
  • 4
  • 24
  • 53
user3299633
  • 2,971
  • 3
  • 24
  • 38
  • This will likely help. https://stackoverflow.com/questions/12152626/how-can-remove-the-extension-of-a-filename-in-a-shell-script – Todd Jan 27 '16 at 01:54
  • Doesn't really help me much. I need to run something for all files in a directory and there might be multiple .text areas. – user3299633 Jan 27 '16 at 01:56
  • What have you tried? Folks here at StackOverflow are willing, even eager to help you solve your programming problems, but we're not short-order coders. Your question should include your attempt to solve this, the results you expected, and the results you got (whether they were errors, or incorrect behaviour). Please update your question. – ghoti Jan 27 '16 at 05:17
  • use `rename` command – tano Jan 27 '16 at 09:33

2 Answers2

1

This should get you started:

#!/bin/bash

for FILE in "$@"; do
  NEWFILE=$(echo $FILE | sed  -re 's/(.*.pdf).*/\1/')
  if [ ! -z "$NEWFILE" -a ! -f "$NEWFILE" -a ! -d "$NEWFILE" ]; then
    mv "$FILE" "$NEWFILE"
  fi
done

But if you have /usr/bin/rename, use it:

 rename 's/(.*\.pdf).*/$1/' *.here
covener
  • 17,402
  • 2
  • 31
  • 45
  • shrug, it should. Try -vn to debug? Maybe just a regex problem. – covener Jan 27 '16 at 02:00
  • What is the *.here doing? And the $1? Am I supposed to type it exactly like that from the directory where the files are? – user3299633 Jan 27 '16 at 02:01
  • `*.here` because you said your original file names are `blabalbal.sometext.here`. For $1, can't you just look into the document once to get some basic understanding? convener has already given you a big hint – Adrian Shum Jan 27 '16 at 02:41
1

Using parameter expansion:

$ ls *.pdf*
file_name1.pdf.sometext.here  file_name2.pdf.blah  file_name3.pdf.sometext
$ for fname in *.pdf*; do mv "$fname" "${fname//.pdf.*/.pdf}"; done
$ ls *.pdf*
file_name1.pdf  file_name2.pdf  file_name3.pdf
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116