当长度未知时,如何从姓氏中删除名字?

Amb*_*tin 5 linux shell text-processing cut

我正在尝试编写一个简单的 bash 脚本,用户在其中输入他们的用户名,然后他们会受到欢迎,具体取决于他们姓氏的时间。我目前有以下几点:

echo Please enter your username
read username
name=$(grep $username /etc/passwd | cut -d ':' -f 5)

h='date +%H'

if [ $h -lt 12]; then
  echo Good morning ${name::-3)
Run Code Online (Sandbox Code Playgroud)

等等等等

我已经设法从那里的名字末尾剪掉了 3 个逗号,但我希望能够剪掉第一个名字。

例如:

  • $nameAmber Martin,,,
  • 我已经减少到Amber Martin.
  • 我需要进一步减少到Martin.
  • 这需要使用任何名称。

ilk*_*chu 11

使用getent passwd/etc/passwd直接阅读更好。getent也适用于 LDAP、NIS 等。我认为它存在于大多数 Unix 中。(我的 OS X 没有它,但它也没有我的帐户/etc/passwd,所以......)

name=$(getent -- passwd "$USER" | cut -d: -f5)
Run Code Online (Sandbox Code Playgroud)

字符串处理可以通过 shell 的参数扩展来完成,这些是 POSIX 兼容的:

name=${name%%,*}         # remove anything after the first comma
name=${name%,,,}         # or remove just a literal trailing ",,,"
name=${name##* }         # remove from start until the last space
echo "hello $name"
Run Code Online (Sandbox Code Playgroud)

使用${name#* }删除直到第一个空格。(只是希望没有人有一个由两部分组成的姓氏,中间有空格)。

cut也可以用文字分裂替换或read通过设置IFS一个冒号。

  • @LucianoAndressMartini,去除前缀和后缀的字符串操作来自POSIX,我认为getent很常见。 (2认同)

Luc*_*ini 5

#!/bin/bash
#And also /bin/sh looks like to be compatible in debian.  
echo "Hmmm... Your username looks like to be $USER"
name="$(getent passwd $USER | cut -d: -f5 | cut -d, -f1)"
echo "Your full name is $name"
surname="$(echo $name | rev | cut -d' ' -f1 | rev)"
echo "Your surname is $surname"
echo "thank your for using only cut and rev to do that..."
echo "But i am sure there is a better way"
Run Code Online (Sandbox Code Playgroud)