简体   繁体   English

将 sed 命令行字符串作为变量传递给 bash

[英]Passing sed command line string to bash as variable

I have a bash script which uses one multi-line sed command to change a file.我有一个 bash 脚本,它使用一个多行 sed 命令来更改文件。 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.我对各种文件使用相同的 bash 脚本。 So I need to pass all of the sed commands from the sending application to the bash script as a single parameter.因此,我需要将来自发送应用程序的所有 sed 命令作为单个参数传递给 bash 脚本。 However, when it passes in from the application, I get only -e.但是,当它从应用程序传入时,我只得到-e。

In the bash script, I have tried a variety of ways to receive the variable as a complete string.在 bash 脚本中,我尝试了多种方法将变量作为完整字符串接收。 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

I assume you invoke your shell script like this我假设您像这样调用您的 shell 脚本

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您在这里要做的是将第 n 个参数存储为文件名,并将前 n-1 个参数存储在数组中

#!/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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM