简体   繁体   English

Bash脚本使用sed替换给定UNIX系统路径的字符串

[英]Bash script using sed to replace string with given UNIX system path

I have the following bash script named SetScript : 我有以下名为SetScript bash脚本:

#!/bin/bash

# make sure CWD is correct location
if [ ! -f $1 ];
then
    echo "No file at \"$1\" found."
    exit 0
fi

sed -i -r "s/^([\t ]+SCRIPT = \")[^\"]*\";\ #\*/\1$2\";\ #\*/" $1

This script is used to change lines like the following in a text file: 此脚本用于更改文本文件中的以下行:

    SCRIPT = "default.script"; #*

The text file is just a config text file that I'm using with the libconfig++ library. 文本文件只是我在libconfig ++库中使用的配置文本文件。

So, for example, if my config text file is named settings.cfg , then I might do this 因此,例如,如果我的配置文本文件名为settings.cfg ,那么我可能会这样做

SetScript settings.cfg another.script

or even this 甚至这个

SetScript settings.cfg "another.script"

These commands would result in the text-file line from above being changed to: 这些命令将导致上面的文本文件行更改为:

    SCRIPT = "another.script"; #*

So far so good. 到现在为止还挺好。 However, when I try to replace with a UNIX path that includes a forward slash, I get issues with sed. 但是,当我尝试使用包含正斜杠的UNIX路径替换时,我遇到了sed问题。 For example: 例如:

$ SetScript settings.cfg "/home/me/some.script"
sed: -e expression #1, char 38: unknown option to `s'
$ SetScript settings.cfg /home/me/some.script
sed: -e expression #1, char 38: unknown option to `s'

My question, then, is: how can I modify my bash script (while still using sed ) to permit replacement by any UNIX system path (relative or full)? 那么我的问题是:如何修改我的bash脚本(同时仍然使用sed )以允许替换任何UNIX系统路径(相对或完整)?

This is because the sed separator you are using is also / , so sed command gets confused when it sees so many slashes. 这是因为您正在使用的sed分隔符也是/ ,因此sed命令在看到如此多的斜杠时会感到困惑。

Try setting another separator, for example _ : 尝试设置另一个分隔符,例如_

sed -i -r "s_^([\t ]+SCRIPT = \")[^\"]*\";\ #\*_\1$2\";\ #\*_" $1
            ^                                  ^            ^

Example

$ echo "he/llo" | sed 's/he/bye/'
byello
$ echo "he/llo" | sed 's/he/llo/bye/'
sed: -e expression #1, char 10: unknown option to `s'
$ echo "he/llo" | sed 's_he/llo_bye_'
bye

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

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