简体   繁体   English

将参数传递给sed命令

[英]Pass parameter into sed command

I am trying to write a bash script in which the user can pass a regex as a parameter. 我正在尝试编写一个bash脚本,用户可以在其中传递一个正则表达式作为参数。 So for example you run the program this way. 因此,例如,您以这种方式运行程序。

./clean_txt.sh s/.*\(my_choices.*gz\)/\1p

In the program, I am using that parameter this way. 在程序中,我以这种方式使用该参数。

ls /home/user/ | sed -n '$1' > cleaned_file.txt
echo "sed -n '$1'"

In my echo, I see the regular expression passed when when program was initiated. 在我的回声中,我看到启动程序时传递的正则表达式。 But my cleaned_file.txt is empty. 但是我的cleaned_file.txt为空。 The only way this works is if I hardcode the a regular expression into the program itself but that defeats the purpose of what I am trying to do. 唯一可行的方法是,如果我将正则表达式硬编码到程序本身中,但是这违背了我试图做的目的。

Any idea on how I can pass that parameter into the sed command? 关于如何将参数传递给sed命令的任何想法吗?

The problem is that your variable is not being expanded. 问题是您的变量没有被扩展。 You need to wrap it in double quotes (which is what you're doing in the echo already): 您需要将其用双引号引起来(这就是您已经在echo执行的操作):

ls /home/user/ | sed -n "$1" > cleaned_file.txt

Note that ls is not needed: 请注意,不需要ls

files=( /home/user/* )
sed -n "$1" <<<"${files[@]}" > cleaned_file.txt

Would do the same thing. 会做同样的事情。 This uses a glob to create an array containing all the filenames, which is used as input to sed. 这使用一个glob创建一个包含所有文件名的数组,该文件名用作sed的输入。

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

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