Skip to content

Instantly share code, notes, and snippets.

@stephenfeather
Last active May 13, 2023 00:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stephenfeather/5ee6cb5f3300da28da4c33ac9c0f0b3d to your computer and use it in GitHub Desktop.
Save stephenfeather/5ee6cb5f3300da28da4c33ac9c0f0b3d to your computer and use it in GitHub Desktop.
Bash script to remove/replace a prefix from woocommerce products
UPDATE wp_postmeta
SET meta_value = REPLACE(meta_value, 'FA-', '')
WHERE meta_key = '_sku'
AND meta_value LIKE 'FA-%'
ORDER BY post_id DESC
LIMIT 10000;
#!/bin/bash
start_time=$(date +%s)
sku_prefix="FA-"
sku_replace=""
batch_size=${1:-1000}
page=${2:-1}
record_count=0
# Calculate the offset based on the page and batch size
offset=$((batch_size * (page - 1)))
# Get a specific range of product IDs based on the offset and batch size
product_ids=$(wp post list --post_type=product --orderby=ID --order=DESC --field=ID --offset=$offset --posts_per_page=$batch_size)
# Get the count of product IDs
count=$(echo "$product_ids" | wc -w)
# Loop through each product ID
for product_id in $product_ids
do
# Get the current SKU
sku=$(wp post meta get $product_id _sku)
# Check if the SKU starts with the prefix
if [[ $sku == $sku_prefix* ]]; then
# Remove the prefix and update the SKU
new_sku=${sku/#$sku_prefix/$sku_replace}
wp post meta update $product_id _sku "$new_sku"
echo "Updated SKU for product ID $product_id: $new_sku"
# This would work on bash
#((record_count++))
#But Ubuntu runs dash
record_count=`expr $record_count + 1`
fi
done
end_time=$(date +%s)
total_time=$((end_time - start_time))
if [ $record_count -gt 0 ]; then
average_time_per_record=$((total_time / record_count))
echo "Processed $record_count of $count records."
echo "Total time taken: $total_time seconds"
echo "Average time per record: $average_time_per_record seconds"
else
echo "No records processed."
echo "Total time taken: $total_time seconds"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment