Modify file name using Python Script - linux

I have many files in my folder with names 1.jpg-xyz, 1.jpg-abc, 2.jpg-qwe etc. I particularly want to move .jpg to the end of each image's name. I can't do it manually since these are thousands in number. I can't get rid of xyz etc after .jpg in the current name since they have important information. So only option I have is to shift .jpg to end. Can somebody tell me what command or script should I use to do that?

This should work:
find *jpg* | while read f ; do g=$(echo "$f" | sed s/\.jpg//) ; echo "mv $f ${g}.jpg" ; done
If the mv commands echoed look like what you want then remove the echo "" around it and re-run.

The below bash code will list all files with .jpg- and move them to -.jpg
re='([^.]+)\.jpg(-.*)'
for file in *.jpg-*
do
if [[ $file =~ $re ]]
then
mv $file "${BASH_REMATCH[1]}${BASH_REMATCH[2]}.jpg"
fi
done

Related

Moving files to subfolders based on prefix in bash

I currently have a long list of files, which look somewhat like this:
Gmc_W_GCtl_E_Erz_Aue_Dl_281_heart_xerton
Gmc_W_GCtl_E_Erz_Aue_Dl_254_toe_taixwon
Gmc_W_GCtl_E_Erz_Homersdorf_Dl_201_head_xaubadan
Gmc_W_GCtl_E_Erz_Homersdorf_Dl_262_bone_bainan
Gmc_W_GCtl_E_Thur_Peuschen_Dl_261_blood_blodan
Gmc_W_GCtl_E_Thur_Peuschen_Dl_281_heart_xerton
The naming pattern all follow the same order, where I'm mainly seeking to group the files based on the part with "Aue", "Homersdorf", "Peuschen", and so forth (there are many others down the list), with the position of these keywords being always the same (e.g. they are all followed by Dl; they are all after the fifth underscore...etc.).
All the files are in the same folder, and I am trying to move these files into subfolders based on these keywords in bash, but I'm not quite certain how. Any help on this would be appreciated, thanks!
I am guessing you want something like this:
$ find . -type f | awk -F_ '{system("mkdir -p "$5"/"$6";mv "$0" "$5"/"$6)}'
This will move say Gmc_W_GCtl_E_Erz_Aue_Dl_281_heart_xerton into /Erz/Aue/Gmc_W_GCtl_E_Erz_Aue_Dl_281_heart_xerton.
Using the bash shell with a for loop.
#!/usr/bin/env bash
shopt -s nullglob
for file in Gmc*; do
[[ -d $file ]] && continue
IFS=_ read -ra dir <<< "$file"
echo mkdir -pv "${dir[4]}/${dir[5]}" || exit
echo mv -v "$file" "${dir[4]}/${dir[5]}" || exit
done
Place the script inside the directory in question make it executable and execute it.
Remove the echo's so it create the directories and move the files.

Get current directory (not full path) with filename only when sub folder is present in Linux bash

I have prepared a bash script to get only the directory (not full path) with file name where file is present. It has to be done only when file is located in sub directory.
For example:
if input is src/email/${sub_dir}/Bank_Casefeed.email, output should be ${sub_dir}/Bank_Casefeed.email.
If input is src/layouts/Bank_Casefeed.layout, output should be Bank_Casefeed.layout. I can easily get this using basename command.
src/basefolder is always constant. In some cases (after src/email(basefolder) directory), sub_directories will be there.
This script will work. I can use this script (only if module is email) to get output. but script should work even if sub directory is present in other modules. Maybe should I count the directories? if there are more than two directories (src/basefolder), script should get sub directories. Is there any better way to handle both scenarios?
#!/bin/bash
filename=`basename src/email/${sub_dir}/Bank_Casefeed.email`
echo "filename is $filename"
fulldir=`dirname src/email/${sub_dir}/Bank_Casefeed.email`
dir=`basename $fulldir`
echo "subdirectory name: $dir"
echo "concatenate $filename $dir"
Entity=$dir/$filename
echo $Entity
Using shell parameter expansion:
sub_dir='test'
files=( "src/email/${sub_dir}/Bank_Casefeed.email" "src/email/Bank_Casefeed.email" )
for f in "${files[#]}"; do
if [[ $f == *"/$sub_dir/"* ]]; then
echo "${f/*\/$sub_dir\//$sub_dir\/}"
else
basename "$f"
fi
done
test/Bank_Casefeed.email
Bank_Casefeed.email
I know there might be an easier way to do this. But I believe you can just manipulate the input string. For example:
#!/bin/bash
sub_dir='test'
DIRNAME1="src/email/${sub_dir}/Bank_Casefeed.email"
DIRNAME2="src/email/Bank_Casefeed.email"
echo $DIRNAME1 | cut -f3- -d'/'
echo $DIRNAME2 | cut -f3- -d'/'
This will remove the first two directories.

batch rename files in ubuntu

I am in need of some command line fu.
I have a wack of files, starting with 4 numbers then a dash then various letters then extentsion, eg.
0851_blahblah_p.dbf
0754_asdf_l.dbf
What I want is to move the four numbers to the end of the filename (keeping the extension in tact) and remove the underscore. Thus the above example would be renamed:
blahblah_p0851.dbf
asdf_l0754.dbf
All help is appreciated.
I am running ubuntu.
Thanks DJ
Here is a solution in pure bash:
for file in *.dbf; do
ext=${file##*.};num=${file%%_*};name=${file%.*};name=${name#*_}
mv $file $name$num"."$ext;
done
Broken down with comments:
for file in *.dbf
do
ext=${file##*.} # Capture the extension
num=${file%%_*} # Capture the number
name=${file%.*} # Step 1: Capture the name
name=${name#*_} # Step 2: Capture the name
mv "$file" "$name$num.$ext" # move the files to new name
done
You can use the rename command:
rename 's/([0-9]{4})_([[:alpha:]]*)_.*.dbf/$2_$1.dbf/' *
You can use sed also
$sed -r 's/([^_]+)_([^.]+)/\2\1/g'
Using this way the given name is splitted and modified as per your requirement.
(or)
Use this script and pass the file names as argument it will move the file name as per the requirement.
#!/bin/sh
if [ $# -ne 1 ] ; then
echo "Usage : <sh filename> <arguments>"
exit ;
fi
for file in $*
do
mv $file `echo $file | sed -r 's/([^_]+)_([^.]+)/\2\1/g' `
done

How to remove the extension of a file?

I have a folder that is full of .bak files and some other files also. I need to remove the extension of all .bak files in that folder. How do I make a command which will accept a folder name and then remove the extension of all .bak files in that folder ?
Thanks.
To remove a string from the end of a BASH variable, use the ${var%ending} syntax. It's one of a number of string manipulations available to you in BASH.
Use it like this:
# Run in the same directory as the files
for FILENAME in *.bak; do mv "$FILENAME" "${FILENAME%.bak}"; done
That works nicely as a one-liner, but you could also wrap it as a script to work in an arbitrary directory:
# If we're passed a parameter, cd into that directory. Otherwise, do nothing.
if [ -n "$1" ]; then
cd "$1"
fi
for FILENAME in *.bak; do mv "$FILENAME" "${FILENAME%.bak}"; done
Note that while quoting your variables is almost always a good practice, the for FILENAME in *.bak is still dangerous if any of your filenames might contain spaces. Read David W.'s answer for a more-robust solution, and this document for alternative solutions.
There are several ways to remove file suffixes:
In BASH and Kornshell, you can use the environment variable filtering. Search for ${parameter%word} in the BASH manpage for complete information. Basically, # is a left filter and % is a right filter. You can remember this because # is to the left of %.
If you use a double filter (i.e. ## or %%, you are trying to filter on the biggest match. If you have a single filter (i.e. # or %, you are trying to filter on the smallest match.
What matches is filtered out and you get the rest of the string:
file="this/is/my/file/name.txt"
echo ${file#*/} #Matches is "this/` and will print out "is/my/file/name.txt"
echo ${file##*/} #Matches "this/is/my/file/" and will print out "name.txt"
echo ${file%/*} #Matches "/name.txt" and will print out "/this/is/my/file"
echo ${file%%/*} #Matches "/is/my/file/name.txt" and will print out "this"
Notice this is a glob match and not a regular expression match!. If you want to remove a file suffix:
file_sans_ext=${file%.*}
The .* will match on the period and all characters after it. Since it is a single %, it will match on the smallest glob on the right side of the string. If the filter can't match anything, it the same as your original string.
You can verify a file suffix with something like this:
if [ "${file}" != "${file%.bak}" ]
then
echo "$file is a type '.bak' file"
else
echo "$file is not a type '.bak' file"
fi
Or you could do this:
file_suffix=$(file##*.}
echo "My file is a file '.$file_suffix'"
Note that this will remove the period of the file extension.
Next, we will loop:
find . -name "*.bak" -print0 | while read -d $'\0' file
do
echo "mv '$file' '${file%.bak}'"
done | tee find.out
The find command finds the files you specify. The -print0 separates out the names of the files with a NUL symbol -- which is one of the few characters not allowed in a file name. The -d $\0means that your input separators are NUL symbols. See how nicely thefind -print0andread -d $'\0'` together?
You should almost never use the for file in $(*.bak) method. This will fail if the files have any white space in the name.
Notice that this command doesn't actually move any files. Instead, it produces a find.out file with a list of all the file renames. You should always do something like this when you do commands that operate on massive amounts of files just to be sure everything is fine.
Once you've determined that all the commands in find.out are correct, you can run it like a shell script:
$ bash find.out
rename .bak '' *.bak
(rename is in the util-linux package)
Caveat: there is no error checking:
#!/bin/bash
cd "$1"
for i in *.bak ; do mv -f "$i" "${i%%.bak}" ; done
You can always use the find command to get all the subdirectories
for FILENAME in `find . -name "*.bak"`; do mv --force "$FILENAME" "${FILENAME%.bak}"; done

Change Names of Multiple Files Linux

I have a number of files with names a1.txt, b1.txt, c1,txt...on ubuntu machine.
Is there any quick way to change all file names to a2.txt, b2.txt, c2.txt...?
In particular, I'd like to replace part of the name string. For instance, every file name contains a string called "apple" and I want to replace "apple" with "pear" in all file names.
Any command or script?
without any extra software you can:
for FILE in *1.txt; do mv "$FILE" $(echo "$FILE" | sed 's/1/2/'); done
for f in {a..c}1.txt; do echo "$f" "${f/1/2}"; done
replace 'echo' with 'mv' if the output looks correct.
and I want to replace "apple" with "linux"
for f in *apple*; do mv "$f" "${f/apple/linux}"; done
The curly brackets in line 1 should work with bash at least.
The following command will rename the specified files by replacing the first occurrence of 1 in their name by 2:
rename 1 2 *1.txt
ls *1.txt | perl -ne 'chomp; $x = $_; $x =~ s/1/2/; rename $_, $x;'
Here's another option that worked for me (following the examples above) for files in different subdirectories
for FILE in $(find . -name *1.txt); do mv "$FILE" "${FILE/1/2}"; done;
Something like this should work:
for i in *1.txt; do
name=$(echo $i | cut -b1)
mv $i ${name}2.txt
done
Modify to suit your needs.

Resources