2

I have this variable:

input_file = file.csv

I want to change the extension of this file from file.csv to file.old

I was thinking about something like mv $input_file basename $input_file . old but I don't really know how to do it

Alessandro
  • 89
  • 2
  • 9

3 Answers3

2

try mv $input_file ${input_file%.*}.old

Deepak Pandey
  • 618
  • 7
  • 19
0
filename="${input_file%.*}"
mv $input_file $filename.old

This should get you sorted

How to extract filename and extension is mentioned here: Extract filename and extension in Bash

Yogesh_D
  • 17,656
  • 10
  • 41
  • 55
0

The below script should work as per your requirement. If you use basename without a suffix(.csv), it returns filename with extension. Also, do not use spaces in between variable declaration and its value.

#/bin/bash
input_file=file.csv
filename="$(basename $input_file .csv)"
mv "$input_file" "$filename.old"

Below is the usage of basename command for your reference.

Usage: basename NAME [SUFFIX]
  or:  basename OPTION... NAME...
Print NAME with any leading directory components removed.
If specified, also remove a trailing SUFFIX.

Mandatory arguments to long options are mandatory for short options too.
  -a, --multiple       support multiple arguments and treat each as a NAME
  -s, --suffix=SUFFIX  remove a trailing SUFFIX; implies -a
  -z, --zero           end each output line with NUL, not newline
      --help     display this help and exit
      --version  output version information and exit

Examples:
  basename /usr/bin/sort          -> "sort"
  basename include/stdio.h .h     -> "stdio"
  basename -s .h include/stdio.h  -> "stdio"
  basename -a any/str1 any/str2   -> "str1" followed by "str2"
JSN
  • 2,035
  • 13
  • 27