BDN*_*BDN 2 linux grep sed awk cut
我怎样才能得到低于输出?我想要第一个字段和空格后的单个字符。
echo "Hello world"
Hellow
Run Code Online (Sandbox Code Playgroud)
如果它还有第 3 个字段,那么第 3 个字段的开始字符应该在输出中。
echo "hello world unix"
hellou
Run Code Online (Sandbox Code Playgroud)
使用 sed:
编辑:由glenn jackmann改进,谢谢!
$ echo "Hello world" | sed -E 's/(\S+).*\s(\S).*$/\1\2/'
Hellow
$ echo "hello world unix" | sed -E 's/(\S+).*\s(\S).*$/\1\2/'
hellou
Run Code Online (Sandbox Code Playgroud)
以“hello world unix”为例进行说明:
s/ 替换以下模式(\S+) 第一组,一个或多个非空格字符:“hello”.* 中间部分,任意字符:“世界”\s 空格字符:" "(\S) 第二组,非空格字符:“u”.*$ 到最后的任何字符:“nix”/\1\2/ 替换为第一组和第二组:“你好”使用 bash:
$ var="Hello world"
$ var_end=${var##* };echo ${var%% *}${var_end:0:1}
Hellow
$ var="hello world unix"
$ var_end=${var##* };echo ${var%% *}${var_end:0:1}
hellou
Run Code Online (Sandbox Code Playgroud)
以“hello world unix”为例进行说明:
var_end=${var##* }删除匹配的前缀模式,最长匹配,${var%% *}删除匹配的后缀模式,最长匹配,${var_end:0:1} 获取第一个字符:“u”用于awk输出与最后一个空格分隔单词的第一个字符连接的第一个空格分隔单词:
awk '{ print $1 substr($NF, 1, 1) }'
Run Code Online (Sandbox Code Playgroud)
该substr()函数从字符串的给定位置返回多个字符,并且$1和$NF分别是当前行上的第一个和最后一个空格分隔的单词。
测试:
$ echo 'hello world' | awk '{ print $1 substr($NF, 1, 1) }'
hellow
Run Code Online (Sandbox Code Playgroud)
$ echo 'apple beet carrot' | awk '{ print $1 substr($NF, 1, 1) }'
applec
Run Code Online (Sandbox Code Playgroud)