find a pattern in files and rename them
I use this command to find files with a given pattern and then rename them to something else
find . -name '*-GHBAG-*' -exec bash -c 'echo mv $0 ${0/GHBAG/stream-agg}' {} \;
As I run this command, I see some outputs like this
mv ./report-GHBAG-1B ./report-stream-agg-1B
mv ./reoprt-GHBAG-0.5B ./report-stream-agg-0.5B
However at the end, when I run ls
, I see the old file names.
You are echo'ing your 'mv' command, not actually executing it. Change to:
find . -name '*-GHBAG-*' -exec bash -c 'mv $0 ${0/GHBAG/stream-agg}' {} \;
I would suggest using the rename
command to perform this task. rename
renames the filenames supplied according to the rule specified as a Perl regular expression.
In this case, you could use:
rename 's/GHBAG/stream-agg/' *-GHBAG-*
In reply to anumi's comment, you could in effect search recursively down directories by matching '**':
rename 's/GHBAG/stream-agg/' **/*-GHBAG-*
This works for my needs, replacing all matching files or file types. Be warned, this is a very greedy search
# bashrc
function file_replace() {
for file in $(find . -type f -name "$1*"); do
mv $file $(echo "$file" | sed "s/$1/$2/");
done
}
I will usually run with find . -type f -name "MYSTRING*"
in advance to check the matches out before replacing.
For example:
file_replace "Slider.js" "RangeSlider.ts"
renamed: packages/react-ui-core/src/Form/Slider.js -> packages/react-ui-core/src/Form/RangeSlider.ts
renamed: stories/examples/Slider.js -> stories/examples/RangeSlider.ts
or ditch the filetype to make it even greedier
file_replace Slider RangeSlider
renamed: packages/react-ui-core/src/Form/Slider.js -> packages/react-ui-core/src/Form/RangeSlider.js
renamed: stories/examples/Slider.js -> stories/examples/RangeSlider.js
renamed: stories/theme/Slider.css -> stories/theme/RangeSlider.css
ReferenceURL : https://stackoverflow.com/questions/15290186/find-a-pattern-in-files-and-rename-them
'programing tip' 카테고리의 다른 글
파일을 열 때 기본값을 펼침으로 설정하는 방법은 무엇입니까? (0) | 2020.12.29 |
---|---|
프로그래밍 방식으로 애플리케이션 지원 폴더 경로 가져 오기 (0) | 2020.12.29 |
반응 형 D3 차트 (0) | 2020.12.29 |
Windows 8의 Grunt : 'grunt'가 인식되지 않음 (0) | 2020.12.29 |
부트 스트랩 모달에서 텍스트 영역 너비를 100 %로 설정 (0) | 2020.12.29 |