當長度未知時,如何從姓氏中刪除名字?

當長度未知時,如何從姓氏中刪除名字?

我正在嘗試編寫一個簡單的 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)

等等等等

我已經設法剪掉名字末尾的 3 個逗號,但我希望能夠剪掉名字。

例如:

  • 是。$nameAmber Martin,,,
  • 我已經削減到了Amber Martin
  • 我需要進一步減少到Martin.
  • 這需要適用於任何名稱。

答案1

使用getent passwd比直接閱讀好/etc/passwdgetent也適用於 LDAP、NIS 等。我認為它存在於大多數 Unix 系統中。 (我的 OS X 沒有它,但它也沒有我的帳戶/etc/passwd,所以...)

name=$(getent -- passwd "$USER" | cut -d: -f5)

字串處理可以透過 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"

使用${name#* }刪除直到第一個空格。 (只是希望沒有人有由兩部分組成的姓氏,中間有空格)。

也可以透過設定為冒號來cut替換為分詞或。readIFS

答案2

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

答案3

一旦你擁有了GECOS(評論)字段,您可以簡單地執行另一個操作cut來刪除(在您的情況下為空)位置和電話號碼字段,這次作為,分隔符號:

name=$(getent passwd "$USER" | cut -d: -f5 | cut -d, -f1)
echo "Hello, ${name##* }-san!"

我將把它作為練習來處理所有不同的可能性什麼是「姓」!

相關內容