我想从一个字符串中提取特定数量的单词。
例如:s1= "Hello: I am new to this forum"
我如何从字符串中提取前4个单词"Hello: I am new"
?
你可以这样做;
#!/bin/bash
s1="Hello: I am new to this forum"
echo $s1 | cut -d' ' -f-4
-d' ':使用空格作为字段分隔符-f-4:字段4及
之前man cut;
-d, --delimiter=DELIM use DELIM instead of TAB for field delimiter -f, --fields=LIST select only these fields; also print any line that contains no delimiter character, unless the -s option is specified
with awk solution;
#!/bin/bash
s1="Hello: I am new to this forum"
echo $s1 | awk '{printf "%s %s %s %sn", $1, $2, $3, $4}'
或只回显;
#!/bin/bash
s1="Hello: I am new to this forum"
echo ${s1/% to*/}
with sed;
#!/bin/bash
s1="Hello: I am new to this forum"
echo $s1 | sed -E 's/(([^ ]+ ){4}).*/1/'