文件x.txt的内容如下:
a 1
b 2
c 3
文件y.txt的内容如下:
absd
cctg
bcgj
scad
请问我怎么用shell命令或者脚本将文件y.txt中的内容替换如下?(即:将y文中的abc替换成x文件中abc对应的数字)
12sd
33tg
23gj
s31d
可以使用 awk 命令读取 x.txt 文件中的内容,并将其存储为一个数组,然后循环读取 y.txt 文件中的每一行内容,查找其中的字符串,如果出现了数组中的某个 key 则将其替换为对应的 value 值。
#!/bin/bash
# 读取数字和字母对应关系到数组中
declare -A arr
while read line; do
key=$(echo $line | awk '{print $1}')
value=$(echo $line | awk '{print $2}')
arr[$key]=$value
done < x.txt
# 循环读取 y.txt 中的每一行,查找其中字符串的对应值并替换
while read line; do
for key in "${!arr[@]}"; do
line=${line//$key/${arr[$key]}}
done
echo $line
done < y.txt
来自microsoft内部技术脚本,现成的powershell脚本:
$x = Get-Content x.txt | ForEach-Object { $_ -split '\\s+' }
$hash = @{}
for ($i=0; $i -lt $x.Length; $i+=2) {
$hash.Add($x[$i], $x[$i+1])
}
Get-Content y.txt | ForEach-Object {
$line = $_
$firstChar = $line.Substring(0, 1)
if ($hash.Contains($firstChar)) {
$line = $line.Replace($firstChar, $hash[$firstChar])
}
Write-Output $line
}
该回答引用chatgpt:亲测可用
#!/bin/bash
# 读取x.txt文件中的内容并保存到关联数组x中
declare -A x
while read -r key value; do
x["$key"]=$value
done < x.txt
# 使用awk命令替换y.txt文件中的内容
awk '{
gsub("a", "'${x["a"]}'", $0);
gsub("b", "'${x["b"]}'", $0);
gsub("c", "'${x["c"]}'", $0);
print $0;
}' y.txt
chmod +x replace.sh
./replace.sh
引用GPT回答:
你可以使用Shell脚本来实现这个替换操作。下面是一个示例脚本:
#!/bin/bash
# 读取文件x.txt的内容,并将键值对存储到关联数组中
declare -A mapping
while read -r key value; do
mapping["$key"]=$value
done < "x.txt"
# 逐行读取文件y.txt,根据关联数组进行替换并输出结果
while IFS= read -r line; do
for key in "${!mapping[@]}"; do
line=${line//$key/${mapping[$key]}}
done
echo "$line"
done < "y.txt"
你可以将上述脚本保存为一个文件,比如replace.sh
,然后在终端中运行以下命令来执行脚本:
chmod +x replace.sh # 赋予脚本执行权限
./replace.sh # 执行脚本
脚本将会读取x.txt
和y.txt
两个文件,然后根据x.txt
中的键值对将y.txt
中的内容进行替换,并输出替换后的结果。在你的例子中,输出结果应该为:
12sd
33tg
23gj
s31d
请确保x.txt
和y.txt
文件位于脚本所在的当前工作目录下,或者提供正确的文件路径以便脚本能够找到它们。