Sandeep Johal
Sandeep Johal

Reputation: 429

Appending and Renaming File in Bash

I've got a file sandeep_mems_SJ_23102003.txt which needs to be renamed sj_new_members_SJ_23102003.txt

I'll be getting these files daily so its vital that anything after _SJ remain the same.

So far I've got the following:-

for each in `/bin/ls -1`;do
  sed -i 's/sandeep_mems_SJ/sj_new_members/g' $each ;
done

Upvotes: 0

Views: 70

Answers (4)

buydadip
buydadip

Reputation: 9417

I tried to replicate your function as much as possible, so here's a solution that implements sed:

for each in *; do
    new=$(echo "$each" | sed 's/.*_SJ/sj_new_members_SJ_/')
    mv $each $new
done

I don't believe you actually need the ls -1 command, as sed will change the filenames of those files that contain the requirements stated above.

In essence, what my command does is save the new file name in a variable, new, and then mv renames it to the filename saved in the variable.

Upvotes: 1

Ivan X
Ivan X

Reputation: 2195

sed would help you if you were changing the contents of files. For renaming the file itself, you could do:

for each in *;do
    mv $each sj_new_members_${each##sandeep_mems_SJ}
done

I used * rather than /bin/ls because it avoids spawning an extra process and uses Bash's built in matching (globbing) mechanism.

Each filename is assigned to $each.

mv renames $each to sj_new_members_ followed by the substring of $each that you want, using Bash's substring mechanism. More details on how to use Bash substrings are here: http://tldp.org/LDP/abs/html/string-manipulation.html

Also, here's an alternative that uses the cut command, which splits along a specified character delimiter, in this case _. I don't like it as much because it spawns a new process, but it works. View the cut man page for more details. Note that $(command) is equalent to using backticks -- it runs a command in a subshell.

for each in *;do
    mv $each sj_new_members_$(cut -d '_' -f 3- <<< $each)
done

Upvotes: 2

Jonatan &#214;str&#246;m
Jonatan &#214;str&#246;m

Reputation: 2609

for each in `/bin/ls -1`;do
  mv $each sj_new_members_SJ${each##*SJ} 
done

The ##*SJ is syntax for parameter expansion for removing everything up to the last SJ. Haven't tested the whole thing but it should work.

Upvotes: 2

anubhava
anubhava

Reputation: 785186

You can use rename utility:

rename 's/sandeep.*?_(\d+\.txt)$/sj_new_members_$1/' sandeep*txt

Upvotes: 1

Related Questions