【问题标题】:Converting user input to uppercase将用户输入转换为大写
【发布时间】:2017-12-08 17:01:52
【问题描述】:

我正在尝试在 Unix 中创建一个程序来访问数据文件,在文件中添加、删除和搜索名称和用户名。使用这个 if 语句,我试图允许用户通过第一个字段搜索文件中的数据。

文件中的所有数据都使用大写字母,所以我首先必须将用户输入的任何文本从小写字母转换为大写字母。出于某种原因,此代码不能同时转换为大写和搜索和打印数据。

我该如何解决?

if [ "$choice" = "s" ] || [ "$choice" = "S" ]; then
        tput cup 3 12
        echo "Enter the first name of the user you would like to search for: "
        tput cup 4 12; read search | tr '[a-z]' '[A-Z]'
        echo "$search"
        awk -F ":" '$1 == "$search" {print $3 " " $1 " " $2 }' 
        capstonedata.txt
fi

【问题讨论】:

  • 我认为添加一些示例数据和预期输出会有所帮助。并解释“这段代码不起作用”是什么意思。
  • 我猜你把文件名放在下一行?您必须将\ 放在末尾以将其视为命令,或者将其放在同一行awk -F ":" '$1 == "$search" {print $3 " " $1 " " $2 }' capstonedata.txt。否则,它将视为单独的命令。
  • 你想要read search ; search=$(echo "$search" | tr '[a-z]' '[A-Z]'; ...。和awk -v srch="$search" '{ ...}。祝你好运。

标签: linux unix awk tr


【解决方案1】:

这个:read search | tr '[a-z]' '[A-Z]' 不会给变量search 赋值。

应该是这样的

read input
search=$( echo "$input" | tr '[a-z]' '[A-Z]' )

而且case modification最好使用参数扩展:

read input
search=${input^^}

【讨论】:

    【解决方案2】:

    如果你使用 Bash,你可以声明一个变量来转换为大写:

    $ declare -u search
    $ read search <<< 'lowercase'
    $ echo "$search"
    LOWERCASE
    

    至于您的代码,read 没有任何输出,因此管道到tr 不会做任何事情,并且在 awk 语句中的文件名之前不能有换行符。

    您的代码的编辑版本,减去所有 tput 内容:

    # [[ ]] to enable pattern matching, no need to quote here
    if [[ $choice = [Ss] ]]; then
    
        # Declare uppercase variable
        declare -u search
    
        # Read with prompt
        read -p "Enter the first name of the user you would like to search for: " search
        echo "$search"
    
        # Proper way of getting variable into awk
        awk -F ":" -v s="$search" '$1 == s {print $3 " " $1 " " $2 }' capstonedata.txt
    fi
    

    或者,如果您只想使用 POSIX shell 结构:

    case $choice in
        [Ss] )
            printf 'Enter the first name of the user you would like to search for: '
            read input
            search=$(echo "$input" | tr '[[:lower:]]' '[[:upper:]]')
            awk -F ":" -v s="$search" '$1 == s {print $3 " " $1 " " $2 }' capstonedata.txt
        ;;
    esac
    

    【讨论】:

      【解决方案3】:

      Awk 不是外壳(谷歌那个)。做吧:

      if [ "$choice" = "s" ] || [ "$choice" = "S" ]; then
              read search
              echo "$search"
              awk -F':' -v srch="$search" '$1 == toupper(srch) {print $3, $1, $2}' capstonedata.txt
      fi
      

      【讨论】:

        猜你喜欢
        • 2012-05-06
        • 2013-07-16
        • 1970-01-01
        • 1970-01-01
        • 2023-03-26
        • 2022-01-24
        • 2014-04-19
        • 2020-04-07
        • 1970-01-01
        相关资源
        最近更新 更多