我编写了一个脚本,以便在不同的情况下显示不同的内容。 脚本是:
#!/usr/bin/env bash
# declare an array, to store stuff in
declare -a myArray
shopt -s nocasematch
# read the full file into the array
# This while loop terminates when pressing CTRL-D
i=1
while read -r line; do
myArray[i]="${line}"
((i++))
done < /dev/stdin
# Process the array
for ((j=1;j<i;++j)); do
# perform your actions here on myArray[j]
case "${myArray[j]}" in
bob)
echo "boy"
;;
alicia)
echo "girl"
;;
cookie)
echo "dog"
;;
*)
echo "unknown" "${myArray[j]}"
;;
esac
done
但是当我使用此命令执行代码时遇到问题:
cat input.txt | ./prog.sh > file.txt
我有以下输入:
bob
alicia
amhed
cookie
daniel
在此输入中,我有足够的空间,但是当我运行程序时,我没有获得正确的结果。我需要我的代码不考虑空格,但如果它考虑空格,则会在 OUTPOUT file.txt 上写入“未知”
我得到结果:
boy
girl
unknown amhed
dog
unknown
unknown
unknown daniel
那么我可以在不触及输入文件的情况下消除/删除空格吗?
最佳答案
为什么在 bash
中这样做?
与awk
$ awk 'BEGIN{n=split("bob boy alicia girl cookie dog",x);
for(i=1;i<n;i+=2) a[x[i]]=x[i+1]} # build the lookup table
{print $1 in a?a[$1]:"unknown "$1}' file
boy
girl
unknown amhed
dog
unknown
unknown
unknown daniel
您也可以将查找映射外部化到另一个文件,这样,如果任一值发生更改,则无需修改代码。
关于bash - 如何用shell脚本删除空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52654853/