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 个逗号,但我希望能够剪掉第一个名字。
例如:
$name
是Amber 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
一个冒号。
#!/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)
归档时间: |
|
查看次数: |
1341 次 |
最近记录: |