Help Needed! - Cut characters after a text string and append to end of filename

Hi all.. I have several unique files that contain one thing in common, and that is acct#. For all files in the directory, I want to append the 10 characters following the word "ACCOUNT:" to the end of the filename.

for example:
I have file 111_123 that contains ACCOUNT:ABC1234567

The file name should change to 111_123.ABC1234567

Any help is much appreciated.

try:

for file in *
do
   acct=$(grep "^ACCOUNT:" "$file" | sed 's/^ACCOUNT: *//')
   [[ -n "$acct" ]] && mv -f "$file" "$file.$acct"
done
1 Like

One way:

cd /path/to/your/dir
for i in *
do
 if [[ -f $i ]]
 then
  str=$(awk 's=index($0,"ACCOUNT:"){print acct=substr($0,s+8,10);exit(0)}' "$i")
  [[ -n $str ]] && echo mv "$i" "$i.$str"
 fi
done

Remove the echo when everything seems alright.

1 Like

Yet another way:

for i in *;do awk -F: '/ACCOUNT/{system("mv -vv "FILENAME" "FILENAME"."$2)}' $i;done
1 Like

Thanks for the quick response guys. I got these to work.

for file in *
do 
  acc=$(sed -n 's/ACCOUNT:\(.\{10\}\)/\1/p' "$file")
  if [ -n "$acc" ]; then
    mv "$file" "$file.$acc"
  fi
done