有什么方法可以在shell脚本中接受没有分隔符的特殊字符? [英] Any way to accept special characters without delimiters in a shell script?

查看:77
本文介绍了有什么方法可以在shell脚本中接受没有分隔符的特殊字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的任务是制作一个 shell 脚本,该脚本交换 2 个字符串,然后输出一个文件.命令类似于:

I'm tasked with a making a shell script that swaps 2 strings and then outputs a file. The commands are similar to:

sed s/search_for/replace/g output.txt >温度数据

sed s/search_for/ replace/g output.txt > temp.dat

mv temp.dat output.txt

mv temp.dat output.txt

脚本是这样工作的:

./myScript var_A var_B output.file 

我可以正常工作.第二部分做同样的事情,但我必须将以下特殊字符视为常规字符串:

Which I got to work fine. The second part does the same thing, but I must treat the following special characters as regular strings:

[ ] ^ * + . $ \ -

我对如何解决这个问题有一个大致的想法(这可能是错误的方式).我想接受这些字符并将它们设置为变量,并在前面附加一个 \.

I have a general idea on how I want to tackle this (this may be the wrong way). I want to accept those characters and set them as variable with a \ appended in the front.

var_A=\\$1
var_B=\\$2

我的问题是 *(星号)和 \(反斜杠)字符.我正在使用一个简单的测试脚本来查看哪些参数可以轻松转换为变量:

My issue is with the * (asterisk) and \ (backslash) characters. I'm using a simple test script to see what parameters I can easily convert to a variable:

for i in "$@"
do
    echo "$i"
done

但 * 字符显示目录中的所有文件,而 \ 显示下一个参数.我知道 set -o noglobset -f,但这些对我不起作用(并且不适用于脚本).我也知道您可以使用反斜杠进行转义,但我也不能使用它.我必须能够接受一个特殊字符(甚至 * 和/)并转换为字符串.我希望这一切都有意义,有人可以帮助我.

But the * char shows all the files in the directory and \ shows the next argument. I know about set -o noglob and set -f, but those will not work for me (and doesn't work on the script). I also know that you can escape using a backslash but I can't use that either. I must be able to take a special character (even * and /) and convert to a string. I hope this all makes sense and someone can help me.

推荐答案

如果我理解正确,你把模式放在变量中,然后你在 sed 中使用这些变量,你需要对待模式作为文字字符串,在正则表达式中没有特殊含义?

If I understand correctly, you put patterns in variables, then you use these variables in sed, and you need to treat the patterns as literal strings, without their special meaning in regular expressions?

如果是这样,那么在将模式传递给 sed 之前,您需要对特殊符号进行转义.这是我的测试的可能实现:

If so, then before passing the patterns to sed, you need to escape the special symbols. Here's a possible implementation with my tests:

#!/bin/sh

escaped() {
    echo "$1" | sed -e 's/[].+-[$\\^*]/\\&/g'
}

set -- [ ] ^ \* + . \$ \\ -
for pat1; do
    pat2=$(escaped "$pat1")
    echo "$pat1 was $pat1" | sed -e s/$pat2/_/
done

escaped 函数接受参数并在特殊字符前放置一个反斜杠.该循环表明以这种方式生成的 pat2 变量与输入字符串中的特殊字符正确匹配.

The escaped function takes the argument and puts a backslash in front of special characters. The loop demonstrates that the pat2 variable generated this way correctly matches the special characters in the input string.

这篇关于有什么方法可以在shell脚本中接受没有分隔符的特殊字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆