gpt4 book ai didi

linux - 使用 unix 查找模式并替换文件内的模式

转载 作者:太空宇宙 更新时间:2023-11-04 05:05:06 25 4
gpt4 key购买 nike

我在 unix 中需要你的帮助。我有一个文件,其中声明了一个值,并且在调用时我必须替换该值。例如我有 &abc 和 &ccc 的值。现在我必须替换 &abc 和 &ccc 的值来代替它们,如输出文件中所示。

输入文件

转到 &abc=ddd;
如果找到文件 &ccc=10;
否,值名称是 &abc;
年龄是 &ccc;

输出:

转到 &abc=ddd;
如果找到文件 &ccc=10;
现在值名称是 ddd;
年龄为 10 岁;

最佳答案

尝试使用 sed。

#!/bin/bash

# The input file is a command line argument.
input_file="${1}"

# The map of variables to their values
declare -A value_map=( [abc]=ddd [ccc]=10 )

# Loop over the keys in our map.
for variable in "${!value_map[@]}" ; do
echo "Replacing ${variable} with ${value_map[${variable}]} in ${input_file}..."
sed -i "s|${variable}|${value_map[${variable}]}|g" "${input_file}"
done

这个简单的 bash 脚本将在给定文件中将 abc 替换为 ddd,将 ccc 替换为 10。这是一个处理简单文件的示例:

$ cat file.txt
so boo aaa abc
duh

abc
ccc
abcccc
hmm
$ ./replace.sh file.txt
Replacing abc with ddd in file.txt...
Replacing ccc with 10 in file.txt...
$ cat file.txt
so boo aaa ddd
duh

ddd
10
ddd10
hmm

关于linux - 使用 unix 查找模式并替换文件内的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17817617/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com