Skip to content

Instantly share code, notes, and snippets.

@ptbrowne ptbrowne/readme.md
Last active Sep 20, 2017

Embed
What would you like to do?
Replace several strings from file

You have a file where you want to replace several strings.

Example :

file.json

[
  {"category": "personalCare"},
  {"category": "atm"},
  {"category": "snaksAndworkMeals"},
  {"category": "shoppingECommerce"},
  {"category": "healthExpenses"},
  {"category": "realEstateLoan"},
  {"category": "activityIncome"},
  {"category": "supermarket"},
  {"category": "supermarket"},
  {"category": "snaksAndworkMeals"},
  {"category": "snaksAndworkMeals"},
  {"category": "shoppingECommerce"},
  {"category": "taxi"},
  {"category": "taxi"},
  {"category": "restaurantsAndBars"},
  {"category": "snaksAndworkMeals"},
  {"category": "snaksAndworkMeals"},
  {"category": "kidsAllowance"},
  {"category": "savings"}
]

replacements.txt

dressing cosmetics
giftsOffered gift_incomes
giftsOffered gifts
healthExpenses health_costs
personalCare home_help
homeInsurance housing_insurance
snaksAndworkMeals meals
realEstateLoan mortgage_refund
electronicsAndMultimedia multimedia
pensionPaid pension
kidsAllowance pocket_money
supermarket regular_shopping
restaurantsAndBars restaurants
activityIncome salary
savings saving_transfer
schoolRestaurant school_restaurant
shoppingECommerce shopping
atm withdrawals

You can run to automatically replace the strings in the first column of replacements.txt by the strings in the second column.

./replace.sh replacements.txt file.json

Result :

[
  {"category": "home_help"},
  {"category": "withdrawals"},
  {"category": "meals"},
  {"category": "shopping"},
  {"category": "health_costs"},
  {"category": "mortgage_refund"},
  {"category": "salary"},
  {"category": "regular_shopping"},
  {"category": "regular_shopping"},
  {"category": "meals"},
  {"category": "meals"},
  {"category": "shopping"},
  {"category": "taxi"},
  {"category": "taxi"},
  {"category": "restaurants"},
  {"category": "meals"},
  {"category": "meals"},
  {"category": "pocket_money"},
  {"category": "saving_transfer"}
]
#!/bin/sh
replacement_file=$1
where=$2
cat $1 | while read line; echo $line | xargs printf "s/%s/%s/g\n" | xargs -I '{}' sed -i.bak '{}' $2; end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.