#!/bin/bash
# NAME: truncate-dname
# PATH: $HOME/askubuntu/
# DESC: Answer for: https://askubuntu.com/questions/1249771/how-to-remove-text-from-a-folder-name-after-a-certain-word/1249785#1249785
# DATE: June 12, 2020
echo ============== CREATE TEST DATA ==================
mkdir -p dnames
cd dnames
mkdir -p "Song Band - Song Name download 9038450985934853434"
mkdir -p "Music List download dkjge3j6lk45j45756567"
mkdir -p "Video Chart download 4k645jel43k5yk574yryryrrtyryrryryrt"
ls
echo ============== RENAME DIRECTORIES ================
for old_name in ./*
do
new_name="${old_name% download*}"
mv -v "$old_name" "$new_name"
done
echo ============== DELETE TEST DATA ==================
ls
cd ..
rm -rf dnames
当你运行脚本时,你会得到这个:
$ truncate-dname
============== CREATE TEST DATA ==================
Music List download dkjge3j6lk45j45756567
Song Band - Song Name download 9038450985934853434
Video Chart download 4k645jel43k5yk574yryryrrtyryrryryrt
============== RENAME DIRECTORIES ================
'./Music List download dkjge3j6lk45j45756567' -> './Music List'
'./Song Band - Song Name download 9038450985934853434' -> './Song Band - Song Name'
'./Video Chart download 4k645jel43k5yk574yryryrrtyryrryryrt' -> './Video Chart'
============== DELETE TEST DATA ==================
Music List Song Band - Song Name Video Chart
您想要的关键操作是在搜索字符串之前提取字符串中的子字符串。例如:
$ a="Song Band - Song Name download 9038450985934853434"
$ b="${a% download*}"
$ echo $b
Song Band - Song Name
如果“下载”一词出现在歌曲标题中,则此过程有点棘手,因此它在文件名中出现了两次:
$ c="People keep downloading my songs download 9038465489643541"
$ d="${c%% download*}"
$ echo $d
People keep
$ d="${c% download*}"
$ echo $d
People keep downloading my songs
这是您需要的代码以及一些您不需要的测试数据:
当你运行脚本时,你会得到这个:
您想要的关键操作是在搜索字符串之前提取字符串中的子字符串。例如:
如果“下载”一词出现在歌曲标题中,则此过程有点棘手,因此它在文件名中出现了两次:
当您有两个
%%
时,它会在您不想要的第一次“下载”事件后删除所有内容。所以在这种情况下,你只想使用一个%
,所以最后一个“下载”是截止点。还有一个
#
你绝对不想要的相反方向搜索的操作:这是一个彻底的参考。