for循环中的变量不是动态的
variable in for loop not dynamic
我制作了一个用户输入一系列字母的脚本
我在脚本中写了这个 for 循环:
#variable that contains the alphabet"
Alphabet="abcdefghijklmnopqrstuvwxyz"
#the user input
Input1=
#the length of the string the user inputs
lengthAlphabetInput=${#1}
for position in `seq 1 $lengthAlphabetInput`
do
letterAtPositionLength=$(($lengthAlphabetInput-$position))
letterAtPosition=$(echo "${Input1:$letterAtPositionLength:1}")
alphabetAtPositionLength=$(($lengthAlphabetInput-$position))
alphabetAtPosition=$(echo "${Alphabet:$alphabetAtPositionLength:1}")
sed "s/$alphabetAtPosition/$letterAtPosition/g" file.txt
done
我预计如果用户输入
./script.sh xyz
它会每
改变一次
- a 和 x
- b 带有 y
- c 带 z
但它只会用 x 替换每个 a。它出于某种原因跳过了其余部分。
谁能帮帮我?
您的 sed
命令没有将结果保存到任何地方,只是将其打印到 stdout
。如果你有 GNU sed,你可以使用 -i
标志来修改文件。例如:
sed -i "s/$alphabetAtPosition/$letterAtPosition/g" file.txt
否则您可以将结果写入临时文件并复制回来:
tmp_file=$(mktemp)
sed "s/$alphabetAtPosition/$letterAtPosition/g" file.txt > "$tmp_file"
mv -f "$tmp_file" file.txt
sed
的其他版本可能具有与 -i
类似的标志,因此请查看您的手册页以了解本地选项。
您的脚本将受益于 sed
的 y
命令,它完全符合您的要求:
$ echo abcdef > a
$ sed 'y/abc/xyz/' a
xyzdef
引用 man page:
y/source/dest/
Transliterate the characters in the pattern space which appear
in source to the corresponding character in dest.
以下是如何在脚本中使用 sed y
:
letters="abcdefghijklmnopqrstuvwxyz"
replacement="" # don't forget the quotes!
letters="${letters:0:${#replacement}}"
sed -i "y/${letters}/${replacement}/" file.txt
请注意此解决方案如何不需要循环并且 reads/writes 文件只需要一次。
我制作了一个用户输入一系列字母的脚本
我在脚本中写了这个 for 循环:
#variable that contains the alphabet"
Alphabet="abcdefghijklmnopqrstuvwxyz"
#the user input
Input1=
#the length of the string the user inputs
lengthAlphabetInput=${#1}
for position in `seq 1 $lengthAlphabetInput`
do
letterAtPositionLength=$(($lengthAlphabetInput-$position))
letterAtPosition=$(echo "${Input1:$letterAtPositionLength:1}")
alphabetAtPositionLength=$(($lengthAlphabetInput-$position))
alphabetAtPosition=$(echo "${Alphabet:$alphabetAtPositionLength:1}")
sed "s/$alphabetAtPosition/$letterAtPosition/g" file.txt
done
我预计如果用户输入 ./script.sh xyz
它会每
改变一次- a 和 x
- b 带有 y
- c 带 z
但它只会用 x 替换每个 a。它出于某种原因跳过了其余部分。
谁能帮帮我?
您的 sed
命令没有将结果保存到任何地方,只是将其打印到 stdout
。如果你有 GNU sed,你可以使用 -i
标志来修改文件。例如:
sed -i "s/$alphabetAtPosition/$letterAtPosition/g" file.txt
否则您可以将结果写入临时文件并复制回来:
tmp_file=$(mktemp)
sed "s/$alphabetAtPosition/$letterAtPosition/g" file.txt > "$tmp_file"
mv -f "$tmp_file" file.txt
sed
的其他版本可能具有与 -i
类似的标志,因此请查看您的手册页以了解本地选项。
您的脚本将受益于 sed
的 y
命令,它完全符合您的要求:
$ echo abcdef > a
$ sed 'y/abc/xyz/' a
xyzdef
引用 man page:
y/source/dest/ Transliterate the characters in the pattern space which appear in source to the corresponding character in dest.
以下是如何在脚本中使用 sed y
:
letters="abcdefghijklmnopqrstuvwxyz"
replacement="" # don't forget the quotes!
letters="${letters:0:${#replacement}}"
sed -i "y/${letters}/${replacement}/" file.txt
请注意此解决方案如何不需要循环并且 reads/writes 文件只需要一次。