简体   繁体   中英

Regex to batch rename files in for loop by only extracting first 5 characters

I have many .xlsx files that look like XXX-A_2016(Final).xlsx and I am trying to write a shell script (bash) that will batch convert each one to csv, but also rename the output file to just "XXX-A.csv", so I think I need a regular expression within my for loop that extracts the first 5 characters of the input string (filename). I have xlsx2csv and I am using the following loop:

for i in *.xlsx;
do
    filename=$(basename "$i" .xlsx);
    outext=".csv" 
    xlsx2csv $i $filename$outext
done

There is a line missing that would take care of the file renaming prior to converting to csv.

You can use:

for i in *.xlsx; do
    xlsx2csv "$i" "${i%_*}".csv
done

"${i%_*}" will strip anything after _ at the end of variable $i , giving us XXX-A as a result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM