Skip to content

Instantly share code, notes, and snippets.

@tolpp
Created August 26, 2022 22:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tolpp/26ff384b477abdad25e9aba2bb299352 to your computer and use it in GitHub Desktop.
Save tolpp/26ff384b477abdad25e9aba2bb299352 to your computer and use it in GitHub Desktop.
replacing filenames using pattern and find command
find . -name '*.txt' -exec sh -c 'x="{}"; mv "$x" "${x//2010/2022}"' \;

Whats under the hood?

  • find command finds the files that ending with *.txt using -name parameter
  • -exec parameter executes move (mv) command for each found file
  • second move argument ${x//2010/2022} replaces string 2010 with 2022 in file names using shell parameter expansion

Files before command:

total 0
drwxr-xr-x   4 user  staff  128 Aug 27 01:41 .
drwxr-xr-x@ 25 user  staff  800 Aug 27 01:39 ..
-rw-r--r--   1 user  staff    0 Aug 27 01:39 a.2010.txt
-rw-r--r--   1 user  staff    0 Aug 27 01:39 b.2010.txt

Files after command:

total 0
drwxr-xr-x   4 user  staff  128 Aug 27 01:42 .
drwxr-xr-x@ 25 user  staff  800 Aug 27 01:39 ..
-rw-r--r--   1 user  staff    0 Aug 27 01:39 a.2022.txt
-rw-r--r--   1 user  staff    0 Aug 27 01:39 b.2022.txt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment