获取一条线的不同部分

Bla*_*ack 2 shell scripting shell-script text-processing

假设我有一行文本如下:

I have a nice car
Run Code Online (Sandbox Code Playgroud)

有没有什么方法可以在不将行保存到任何文件的情况下分别在不同位置获取行的不同单词(例如,我想获得“有”和“不错”的部分)。我的意思是,我想应用这样一种方法,它会直接在给定行的所需位置给我单词。有什么办法吗?

tac*_*omi 5

使用awk试试这个:

$ awk '{print $2, $4}' file
Run Code Online (Sandbox Code Playgroud)

$x单词位置在哪里,这是由空格分隔的

例如

$ echo "I have a nice car" | awk '{print $2, $4}'
have nice
Run Code Online (Sandbox Code Playgroud)


gle*_*man 5

bash 有数组:

line="I have * nice car"
set -f                      # disable pathname expansion
words=($line)               # no quotes around $line
set +f                      # re-enable pathname expansion
Run Code Online (Sandbox Code Playgroud)

words 是一个索引数组,从零开始,所以

# print the 2nd word
echo "${words[1]}"               # ==> have

# print the 2nd-last word
echo "${words[-2]}"              # ==> nice
Run Code Online (Sandbox Code Playgroud)

将字符串转换为数组会在 shell$IFS变量中包含的任何字符序列处拆分字符串(默认值:空格、制表符、换行符)