Karim
Karim

Reputation: 291

sed not working on a variable within a bash script; requesting a file. Simple example

If I declare a variable within a bash script, and then try to operate on it with sed, I keep getting errors. I've tried with double quotes, back ticks and avoiding single quotes on my variable. Here is what I'm essentially doing.

Call my script with multiple parameters

./myScript.sh apples oranges ilike,apples,oranges,bananas

My objective is to use sed to replace $3 "," with " ", then use wc -w to count how many words are in $3.

MyScript.sh

fruits="$3"
checkFruits= sed -i 's/,/ /g' <<< "$fruits"
echo $checkFruits

And the result after running the script in the terminal:

ilike,apples,oranges,bananas
sed: no input files

P.s. After countless google searches, reading suggestions and playing with my code, I simply cannot get this easy sample of code to work and I'm not really sure why. And I can't try to implement the wc -w until I move past this block.

Upvotes: 2

Views: 1042

Answers (4)

chepner
chepner

Reputation: 531205

You don't need sed at all.

IFS=, read -a things <<< "$3"
echo "${#things[@]}"

Upvotes: 1

oguz ismail
oguz ismail

Reputation: 50760

The -i option is for inplace editing of input file, you don't need it here.

To assign a command's output to a variable, use command expansion like var=$(command).

fruits="$3"
checkFruits=$(sed 's/,/ /g' <<< "$fruits")
echo $checkFruits

Upvotes: 1

Walter A
Walter A

Reputation: 20002

You can do

fruits="$3"
checkFruits="${3//,/ }"
# or 
echo "${3//,/ }"

Upvotes: 4

Jeff Breadner
Jeff Breadner

Reputation: 1438

The -i flag to sed requires a file argument, without it the sed command does what you expect.

However, I'd consider using tr instead of sed for this simple replacement:

fruits="$3"
checkFruits="$(tr , ' ' <<< $fruits)"
echo $checkFruits

Looking at the larger picture, do you want to count comma-separated strings, or the number of words once you have changed commas into spaces? For instance, do you want the string "i like,apples,oranges,and bananas" to return a count of 4, or 6? (This question is moot if you are 100% sure you will never have spaces in your input data.)

If 6, then the other answers (including mine) will already work.

However, if you want the answer to be 4, then you might want to do something else, like:

fruits="$3"
checkFruits="$(tr , \\n <<< $fruits)"
itemCount="$(wc -l <<< $checkFruits)"

Of course this can be condensed a little, but just throwing out the question as to what you're really doing. When asking a question here, it's good to post your expected results along with the input data and the code you've already used to try to solve the problem.

Upvotes: 3

Related Questions