简体   繁体   中英

Pass parameter into sed command

I am trying to write a bash script in which the user can pass a regex as a parameter. 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. 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?

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):

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

Note that ls is not needed:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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