How to rename multiple files by adding word from that file?

I have files :

file name: report_2020-10-13-17-11.txt
Contain :

this report was prepared by=John

file name: report_2020-10-13-17-12.txt
Contain :

this report was prepared by=Doe

file name: report_2020-10-13-17-13.txt
Contain :

this report was prepared by=Ton

file name: report_2020-10-14-07-25.txt
Contain :

this report was prepared by=Bolt

I want to rename the files become

John_report_2020-10-13-17-11.txt
Doe_report_2020-10-13-17-12.txt
Ton_report_2020-10-13-17-13.txt
Bolt_report_2020-10-14-07-25.txt

thanks


Answer

Untested

for file in report_*.txt; do
    owner=$( grep -Po '(?<=this report was prepared by=)\w+' "$file" )
    echo mv "$file" "${owner}_$file"
done

If the results look OK, remove “echo”

Attribution
Source : Link , Question Author : Mayang Sari , Answer Author : glenn jackman

Leave a Comment