简体   繁体   English

Bash-搜索并追加字符串

[英]Bash - Search and append strings

If I wanted to search for a line in a file and append a string to the end of that line, how can I go about it? 如果我想在文件中搜索一行并将一个字符串附加到该行的末尾,该如何处理? IE: IE浏览器:

file=?

I want to search for file=? 我要搜索file=? and replace the question mark with a file path. 并用文件路径替换问号。 The file path is located in a variable $FILEPATH 文件路径位于变量$FILEPATH

file=$FILEPATH

Thanks! 谢谢!

EDIT 编辑

sed -i -f "s,file=\?,file=$FILEPATH,g"

The above works well and is what I'm looking for but is there a way to replace the question mark? 上面的方法效果很好,是我在寻找什么,但是有没有办法替换问号? With the code above if I have the following: 使用上面的代码,如果我具有以下内容:

FILEPATH=/file/path

Properties file: 属性文件:

something=?
file=?

The replacement produces: 替换产生:

Properties file: 属性文件:

something=?
file=/file/path?

Is there a way to replace the ? 有办法替换? completely? 完全吗?

I'd use sed for that: 我会为此使用sed:

sed -i "s/file=?/file=$FILEPATH/g" your_file

If your $FILEPATH has / then use a different sed separator, something like: 如果您的$FILEPATH具有/则使用不同的sed分隔符,例如:

sed -i "s,file=?,file=$FILEPATH,g"

Don't escape your question mark 不要逃避你的问号

[jaypal:~/Temp] cat temp
file=?
file=?

[jaypal:~/Temp] echo $filepath
/usr/bin

[jaypal:~/Temp] sed -e 's_file=?_file='$filepath'_g' temp
file=/usr/bin
file=/usr/bin

Also to make inline changes I would recommend to use the following - 另外,为了进行内联更改,我建议使用以下内容-

[jaypal:~/Temp] sed -ibak 's_file=?_file='$filepath'_g' temp

[jaypal:~/Temp] ls temp*
temp    tempbak

[jaypal:~/Temp] cat temp
file=/usr/bin
file=/usr/bin

[jaypal:~/Temp] cat tempbak
file=?
file=?

This will make a backup copy of your original file before making any changes. 进行任何更改之前,这将为您的原始文件创建备份。 In case if anything goes wrong you will have your original copy protected. 万一出问题了,您的原始副本将受到保护。

If you are using Bash, you can simply use Bash builtins and substitutions instead of sed: 如果您使用的是Bash,则可以简单地使用Bash内置函数和替代函数来代替sed:

#!/bin/bash

FILEPATH="/file/path"

while read line; do
    echo "${line/file=\?/${line/\?/}$FILEPATH}"
done < yourfile

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

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