Bash Ubuntu:删除字符串的一部分

Bash Ubuntu:删除字符串的一部分,bash,shell,csv,ubuntu,terminal,Bash,Shell,Csv,Ubuntu,Terminal,我想使用Ubuntu终端重命名文件夹中的几百个文件,因为我不允许安装任何东西 文件的名称采用以下格式: ER201703_公司_名称_某物_9876543218_90087625374823.csv 之后应该是这样的: ER201703_9876543218_90087625374823.csv 所以,我想删除中间部分(公司名称),它有时有2个、3个甚至4个。我想创建两个字符串;一个用于前部,一个用于后部。前面的部分很容易,而且已经开始工作了,但是后面的部分我正在努力 for name in *

我想使用Ubuntu终端重命名文件夹中的几百个文件,因为我不允许安装任何东西

文件的名称采用以下格式: ER201703_公司_名称_某物_9876543218_90087625374823.csv 之后应该是这样的: ER201703_9876543218_90087625374823.csv

所以,我想删除中间部分(公司名称),它有时有2个、3个甚至4个。我想创建两个字符串;一个用于前部,一个用于后部。前面的部分很容易,而且已经开始工作了,但是后面的部分我正在努力

for name in *.csv;
do
    charleng=${#name};
    start=$(echo "$name" | grep -a '_9');
    back=$(echo "$name" | cut -c $start-);
    front=$(echo "$name" | cut -c1-9);  
    mv "$name""$front$back";
done
我试图找到9的位置,并保持从那里到字符串末尾的所有内容

致意 一月

例如:

kent$  awk -F'_' '{printf "mv %s %s_%s_%s\n",$0,$1,$(NF-1),$NF}' <<<"ER201703_Company_Name_Something_9876543218_90087625374823.csv"                                         
mv ER201703_Company_Name_Something_9876543218_90087625374823.csv ER201703_9876543218_90087625374823.csv

kent$awk-F''{printf“mv%s%s\u%s\n',$0,$1,$(NF-1),$NF}'如果安装了
rename
(我认为Ubuntu就是这样),您可以使用以下命令而不是循环

rename -n 's/^(ER\d*)\w*?(_9\w*)/$1$2/' *.csv
删除
-n
(无操作)以应用更改

解释
  • s/../../
    用右模式替换左正则表达式的匹配项
  • (ER\d*)
    匹配第一部分(
    ER
    后接一些数字),并将其存储在
    $1
    中供以后使用
  • \w*?
    匹配公司部分,即尽可能少的(非贪婪的)单词字符(字母、数字、下划线等)
  • (\u 9\w*)
    匹配第二部分,并将其存储在
    $2
    中供以后使用
  • $1$2
    是先前匹配零件的替代品。我们只省略了公司部分

我可以提供替代解决方案,可能更通用

rename 's/^([^_]+(?=_))(?:\w+(?=_\d+))(_\d+_\d+\.csv)$/$1$2/' *.csv
如果希望使用健壮的正则表达式,日志的名称将发生更改

([^_]+(?=_)) - match everything that not underscore till the first one and store it to $1
(?:\w+(?=_\d+)) - match chars until the numbers but (?:...) not store to var
(_\d+_\d+\.csv) -  match set of numbers and file extension and store it to $2

哇!这比预期的更容易理解!非常感谢你!或者,如果您知道要删除的部分只包含字母,而其余部分则以其他部分开始,如数字,则类似于
rename-n“s/\u[a-zA-Z+\u/\u/”
也可以。
([^_]+(?=_)) - match everything that not underscore till the first one and store it to $1
(?:\w+(?=_\d+)) - match chars until the numbers but (?:...) not store to var
(_\d+_\d+\.csv) -  match set of numbers and file extension and store it to $2