我有一个脚本,在一个变量词中,我在文件中,在其他变量中,我有单词,我想使用而不是第一个变量中的单词。我需要找到i am scatman
并将这些字词替换为you are dukenukem
。例如,我的文本文件wwe.txt
:
i
am
dsadsa
sda
daaaa
ds
dsds
dsa
d
scatman
例如,我写了一个脚本,它创建了grep,它起作用了:
words="i am scatman"
echo "$words"
for i in $words; do
if grep -q "$i" wwe.txt; then
echo "these words are exists"
grep "$i" wwe.txt
else
echo "these words are not exists"
exit 1
fi
done
有效。但如果我想,替换这些话,我该怎么做呢?我写了这个:
words="i am scatman"
words2="you are dukenukem"
for i in $words; do
for y in $words2; do
if grep -q "$i" wwe.txt; then
echo "these words are exists"
grep "$i" wwe.txt
sed -i 's/'"$i"'/'"$y"'/g' wwe.txt
else
echo "these words are not exists"
exit 1
fi
done
done
但它不起作用,我有错误?请帮助。
答案 0 :(得分:0)
此代码有效。请试一试。
#!/bin/bash
line1="i am scatman"
line2="you are dukenukem"
words2=($line2)
count=0
for word in $line1; do
sed -i -e "s/$word/${words2[$count]}/g" wwe.txt
count=$((count + 1))
done