1

Take a number of files named:

data_a_LT.fits
data_a_LT.coo
data_a_LT.ec
data_a_LT.grp

I want to replace all "a_LT" with "LT_A" such that I have:

data_LT_A.fits
data_LT_A.coo
data_LT_A.ec
data_LT_A.grp

How does one do this with one command. Something like:

mv *a_LT* *LT_A*
1
  • 1
    Do you want one command, or a one-liner? Is a function ok?
    – Anthon
    Commented Sep 19, 2014 at 14:45

5 Answers 5

3

Using bash:

for file in *; do [[ -f "$file" ]] && mv "$file" "${file/a_LT/LT_A}"; done
data_LT_A.coo
data_LT_A.ec
data_LT_A.fits
data_LT_A.grp
2

If rename is available use this command:

rename 's/a_LT/LT_A/' *

Another approach with awk:

find -type f | awk -F'a_LT' '{printf "mv \"%s\" \"%sLT_A%s\"\n", $0, $1, $2}' | bash
1
  • 1
    The rename command varies depending on OS and distro. There is one that comes with perl and another that comes with util-linux.
    – jordanm
    Commented Sep 19, 2014 at 6:22
2

I'm used to using xargs:

ls -1 | sed 's/\(\(.*\)a_LT\(.*\)\)/\1 \2LT_A\3/' | xargs -n 2 mv
3
  • 2
    Those are three commands, the OP asked one command.
    – Anthon
    Commented Sep 19, 2014 at 8:43
  • 1
    define "one command" ;-)
    – smrt28
    Commented Sep 19, 2014 at 12:39
  • 1
    one command less: :-D echo "ls -1 | sed 's/((.*)a_LT(.*))/\1 \2LT_A\3/' | xargs -n 2 mv" | sh
    – smrt28
    Commented Sep 19, 2014 at 12:41
0

rename might not work as expected in CentOS based systems.. In that case, you can download this script and copy it in your machine as $HOME/bin/rename.pl.

rename.pl 's/a_LT/LT_A/g' * -vn

will work as expected now..

It's better to run

rename.pl -n 's/a_LT/LT_A/g' *

before running the first command, as this will display the would be output without actually changing the names.

2
  • 1
    Why should he need to copy it to /usr/bin? It will be overwritten next time util-linux is upgraded.
    – jordanm
    Commented Sep 19, 2014 at 6:22
  • 1
    Didn't think of it.. edited now. Thanks.
    – Gokul
    Commented Sep 19, 2014 at 6:25
0

I went for the following which worked a treat.

rename 's/a_LT/LT_A/g' *

One liner, concise and easy to remember.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .