Insert a date before the suffix of all the json files in a directory

for i in `ls`; do mv "$i" "`echo $i | sed s/.json/_20160428.json/`"; done

By: rdc
2016-04-29 12:32:22

What Others Think

Urgh! That's not pretty. Let's assume you don't have (or know how to use) the rename command. . First, don't parse the output of ls, it's just an accident waiting to happen. If you only want to rename json files, then this will do. for i in *.json; do ... done . Next, it's a good habit to use $(command) rather than `command`. They can be nested and the quoting inside is more robust. . Do you really want a hard-coded date? Wouldn't today's date be a more useful command: date '+%Y%m%d' . If you're using bash you can get rid of sed using variable expansion, e.g. remove suffix: ${i%.json} . So a better command might look like: for i in *.json; do mv "$i" "${i%.json}_$(date '+%Y%m%d').json"; done
flatcap · 252 weeks and 4 days ago
In addition to what @flatcap said, if available, you can use `rename`. It's not available everywhere, so this command is not as portable as his, but it is simpler. rename "s/.json/_$(date '+%Y%m%d').json" *.json
goodevilgenius · 252 weeks and 4 days ago

What do you think?

Any thoughts on this command? Does it work on your machine? Can you do the same thing with only 14 characters?

You must be signed in to comment.

What's this? is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.

Share Your Commands

Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.


Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for: