1

I am trying to store the start of a sed command inside a variable like this:

sedcmd="sed -i '' "

Later I then execute a command like so:

   $sedcmd s/$orig_pkg/$package_name/g $f

And it doesn't work. Running the script with bash -x, I can see that it is being expanded like:

   sed -i ''\'''\''' 

What is the correct way to express this?

1

5 Answers 5

3

Define a shell function:

mysed () {
    sed -i "" "$@"
}

and call it like this:

$ mysed s/$orig_pkg/$package_name/g $f
Sign up to request clarification or add additional context in comments.

1 Comment

I missed that @larsman suggest this at the end of his answer.
2

It works when the command is only one word long:

$ LS=ls
$ $LS

But in your case, the shell is trying the execute the program sed -i '', which does not exist.

The workaround is to use $SHELL -c:

$ $SHELL -c "$LS"
total 0

(Instead of $SHELL, you could also say bash, but that's not entirely reliable when there are multiple Bash installations, the shell isn't actually Bash, etc.)

However, in most cases, I'd actually use a shell function:

sedcmd () {
    sed -i '' "$@"
}

Comments

0

Why not use an alias or a function? You can do alias as

alias sedcmd="sed -i '' "

2 Comments

Testing it like: #!/bin/bash alias sedcmd="sed -i '' " sedcmd gives: ./test.sh: line 4: sedcmd: command not found
Aliases are not enabled by default in non-interactive shells, which is one reason to use a shell function instead. But you can turn on aliases using shopt -s expand_aliases.
0

Not exactly sure what you're trying to do, but my suggestion is:

sedcmd="sed -i "
$sedcmd s/$orig_pkg/$package_name/g $f

You must set variables orig_pkg package_name and f in your shell first.

If you're replacing variable names in a file, try:

$sedcmd s/\$orig_pkg/\$package_name/g $f

Still f must be set to the file name you're working on.

Comments

0

This is the right way for do that

alias sedcmd="sed -i ''"

Obviously remember that when you close your bash, this alias will be gone.
If you want to make it "permanent", you have to add it to your .bashrc home file (if you want to make this only for a single user) or .bashrc global file, if you want to make it available for all users

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.