简体   繁体   中英

In Bash, can a “mv-for loop” be done on one line?

I frequently require to type

#!/usr/bin/bash
for i in files-*
do
    mv $i ${i/files/items}
done

Can this be done simpler?

In one line: yes. Simpler: probably not.

for i in files-*; do mv "$i" "${i/files/items}"; done

If you need something like this frequently, you could encapsulate it in a function and just call that function. Or define some sort of template/text block/macro in your preferred editor.

如果安装了perl ,则可以使用rename

rename 's/files/items/' files-*

It won't get a lot shorter than what Ansgar already suggested. However, you can save some typing via a couple of mechanisms:

Bash command history

Use bash's command history to recall the command. Not exactly hi-tech, but this cann save you a lot of typing, and you don't have to save/alter whatsoever on your system.

A script file

Put the command in a script file you save somewhere in your path.

 #/bin/bash
 for i in files-*; do 
     mv $i ${i/files/items} 
 done

In this case I'd leave the multiple lines intact to optimize readabilty

Alias

Add an alias for the command to your .bashrc file

 alias movem='for i in files-*; do mv $i ${i/files/items}; done'

Once you've done that, just typing the alias will allow you to run the command. One advantage of this is that you don't have to create a script file.

ps: /usr/bin/bash ??? What system are you using?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM