Zayan Shariff
Zayan Shariff

Reputation: 9

How to add single quotes in a shell script using sed

Need help in making a sed script to find and replace user input along with single quotes. Input file admins.py:

Script:

                       read adminsid
                       while [[ $adminsid == "" ]];
                               do
                               echo "You did not enter anything. Please re-enter AdminID"
                               read adminsid 
                               done

## Please enter Admin's ID
9999999999,8888888888,1111111111

## Script To Replace ADMIN_IDS = [] to ADMIN_IDS = ['9999999999,8888888888,1111111111'] in file
   sed -i "s|ADMIN_IDS = \[.*\]|ADMIN_IDS = ['$adminsid']|g" $file

## Current results:

   ADMIN_IDS = ['9999999999,8888888888,1111111111']

## Expected results:

   ADMIN_IDS = ['9999999999','8888888888','1111111111']

Upvotes: 1

Views: 2131

Answers (5)

Gill
Gill

Reputation: 1

echo "('${adminsid//,/\\',\\'}')"

Upvotes: 0

Walter A
Walter A

Reputation: 20002

Replace the , with ',' in the variable and add characters at the beginning and at the end.

sed "s/.*/['&']/" <<< "${adminsid//,/','}"

Upvotes: 0

suspectus
suspectus

Reputation: 17268

Assign the variable to the data

adminsid=9999999999,8888888888,1111111111

Then use sed -e (script) option to add the quoting, and square brackets.

echo "$adminsid" | sed -e "s/,/\',\'/g" -e "s/^/[\'/" -e "s/$/\']/"

or to apply changes to a file (filename in $file):

sed -i "$file" -e "s/,/\',\'/g" -e "s/^/[\'/" -e "s/$/\']/"

Upvotes: 1

potong
potong

Reputation: 58430

This might work for you (GNU sed & bash):

<<<"$adminsid" sed 's/[^,]\+/'\''&'\''/g;s/.*/[&]/'

Surround all non-comma characters by single quotes and then surround the entire string by square brackets.

Upvotes: 0

ashish_k
ashish_k

Reputation: 1581

You can do this with awk too:

Suppose you have assigned the variable as :

adminsid=9999999999,8888888888,1111111111

Then the solution:

echo "$adminsid"| awk -F"," -v quote="'" -v OFS="','" '$1=$1 {print "["quote $0 quote"]"}'
  1. -F"," -v OFS="','" :: Replacing separator (,) with (',')
  2. print "["quote $0 quote"]" :: Add single quotes(') and ([) and (]) to the begin and end of line

Upvotes: 0

Related Questions