bash - 如何用shell脚本删除空格?

标签 bash shell

我编写了一个脚本,以便在不同的情况下显示不同的内容。 脚本是:

#!/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/

相关文章:

json - 使用 jq 合并 2 个 JSON 对象

regex - 以 "n"结尾的所有条目的正则表达式

bash - SED 命令在 Vagrant Init 脚本中不起作用

bash - 在 bash 中只保留第一个重复条目

bash- 修剪 txt 文件中的偶数行

php - 从 PHP 调用 "grep"和 "head"

linux - 如何在从 scp 接收文件后运行脚本

linux - Bash 脚本解析 HTML 文件

linux - 用于验证Linux上make版本的Shell脚本

linux - 从多个子目录中删除文件,但在每个子目录中保留 3 个最新文件