0

I have a bash script which uses one multi-line sed command to change a file. From the command line, this line works:

sed -e '1a\' -e '/DELIMITER="|" \' -e '/RESTRICT_ADD_CHANGE=1 \' -e '/FIELDS=UPDATE_MODE|PRIMARYKEYVALUE|PATRONFLAGS' -e '1 d' general_update_01 > general_update_01.mp

I use the same bash script for a variety of files. So I need to pass all of the sed commands from the sending application to the bash script as a single parameter. However, when it passes in from the application, I get only -e.

In the bash script, I have tried a variety of ways to receive the variable as a complete string. None of these store the variable.

sed_instructions=$(echo $6)
sed_instructions=$6
sed_instructions=$(eval "$6")

and a few other configurations.

My command line would use the variable like this:

sed $sed_instructions $filename > $filename.mp
3
  • You don't show how you invoke your bash script. Commented Jan 13, 2022 at 19:18
  • 2
    "I need to pass all of the sed commands [...] as a single parameter" -- why do you think that? Commented Jan 13, 2022 at 19:18
  • 1
    BashFAQ #50 is relevant: I'm trying to put a command in a variable, but the complex cases always fail! Commented Jan 13, 2022 at 19:30

1 Answer 1

3

I assume you invoke your shell script like this

script.sh -e '1a' -e '/DELIMITER="|" ' -e '/RESTRICT_ADD_CHANGE=1 ' -e '/FIELDS=UPDATE_MODE|PRIMARYKEYVALUE|PATRONFLAGS' -e '1 d' general_update_01

What you want to do here is store the nth parameter as the filename, and the first n-1 parameters in an array

#!/usr/bin/env

n=$#
filename=${!n}
sed_commands=("${@:1:n-1}")

# Now, call sed
sed "${sed_commands[@]}" "$filename" > "${filename}.mp"

To demonstrate that code in action:

$ set -- one two three four
$ n=$#
$ filename=${!n}
$ args=("${@:1:n-1}")
$ declare -p filename args
declare -- filename="four"
declare -a args=([0]="one" [1]="two" [2]="three")
Sign up to request clarification or add additional context in comments.

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.