[英]Python or Shell assistance: How to search for a word and replace only the value next to it
I have a text file (list.txt) with the following format: 我有一个具有以下格式的文本文件(list.txt):
Apple 1
Banana 5.0
orange_1 0.5
The list can go on for many lines. 该列表可以持续很多行。 I would like to ultimately search for the word "Apple" and only replace the value next to it. 我想最终搜索“ Apple”一词,仅替换其旁边的值。 I know how to use a "sed" command that can search and replace a word but I don't know how I can search for a word and replace only the value next to it? 我知道如何使用可以搜索和替换单词的“ sed”命令,但是我不知道如何搜索单词并仅替换单词旁边的值?
the sed command I use in my script is as follows: 我在脚本中使用的sed命令如下:
sed "s/Apple/$1/g" list.txt > newlist.txt
where $1 is defined in a run script and could be anything (eg grape). $ 1是在运行脚本中定义的,可以是任何值(例如grape)。 Again this would switch the word Apple and not the value next to it. 同样,这将切换“ Apple”一词,而不是其旁边的值。 I would like to be able to perform this action either by using a SHELL or Python command. 我希望能够通过使用SHELL或Python命令来执行此操作。 Any help would be fantastic! 任何帮助都太棒了!
Here I show positive lookback way as @ryugie said: 在这里,我表现出积极的回溯方式,如@ryugie所说:
content = '''Apple 1
Banana 5.0
orange_1 0.5'''
def my_replace(content, fruit, value):
import re
return re.sub(r'(?<=' + fruit + ' )([\d\.]+)', str(value), content)
print my_replace(content, 'Apple', 4.0)
print my_replace(content, 'Banana', 1.5)
And we can get: 我们可以得到:
Apple 4.0
Banana 5.0
orange_1 0.5
Apple 1
Banana 1.5
orange_1 0.5
Assuming that each line starts with the key and the value is the rest of the line after a space, you can use the following sed
command to replace only the value: 假设每行以键开头,并且值是空格后的其余行,则可以使用以下sed
命令仅替换值:
sed "s/\(^Apple \)\(.*$\)/\1$1/"
Please note that this might be a fragile/insecure solution depending on the replacement value, eg if $1
contains /
, it can be used for a command insertion like /;d;s//
. 请注意,这可能是一个脆弱/不安全的解决方案,具体取决于替换值,例如,如果$1
包含/
,它可以用于/;d;s//
类的命令插入。
A more robust solution with awk
: 使用awk
更强大的解决方案:
awk -v new="$1" '{print ($1 == "Apple") ? ($1 " " new) : $0}'
UPD. UPD。 Both commands can work with files either directly or via standard streams: 这两个命令都可以直接或通过标准流使用文件:
sed ... file.txt > new.txt
cat file.txt | sed ... | cat > new.txt
(do not use cat
like this, it's here to show piped input/output). (不要像这样使用cat
,它在这里显示管道输入/输出)。 Additionally, some versions of sed
have option -i
to change file in place: 此外,某些版本的sed
具有选项-i
来更改文件位置:
sed -i ... file.txt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.