|
Title: shell script: print text characters no more than 6 words, is a business interview questions, topics are as follows:
for loop prints the following sentence is not more than the number of letters in the word. 6;
I am oldboy teacher welcome to oldboy traning class
method 1:
Using an array a, store the text in a word; for cyclic polling, if judging the length of each word printed word or less 6;
[Root @ localhost anglea] # cat 1.sh
#! / Bin / bash
#written by linuxidc @ 2015-10-28
a = (I am oldboy teacher welcome to oldboy traning class)
for ((i = 0; i <$ {# a [*]}; i ++))
do
if [$ {# a [$ i]} -le 6]
then
echo $ {a [$ i]}
fi
done
The above can also determine if expr length determine string length;
[Root @ localhost anglea] # cat 1.sh
#! / Bin / bash # written by linuxidc @ 2015-10-28
a = (I am oldboy teacher welcome to oldboy traning class)
for ((i = 0; i <$ {# a [*]}; i ++))
do
if [ `expr length $ {a [$ i]}` -le 6]
then
echo $ {a [$ i]}
fi
done
Another method of the array: directly read the array elements determine the length of the element;
arr = (I am oldboy teacher welcome to oldboy traning class)
for file in $ {arr [@]}
do
if [$ {# file} -le 6]
then
echo $ file
fi
done
Execution results are as follows:
[Root @ localhost anglea] # sh 1.sh
I
am
oldboy
to
oldboy
class
Method 2:
Use for polling loop word, use wc -L judgment word length, and make a judgment;
[Root @ localhost anglea] # cat 2.sh
#! / Bin / bash # written by linuxidc @ 2015-10-28
for f in I am oldboy teacher welcome to oldboy traning class
do
[ `Echo $ f | wc -L` -le 6] && echo $ f
done
Execution results are as follows:
[Root @ localhost anglea] # sh 2.sh
I
am
oldboy
to
oldboy
class
Method 3: awk usage of length
[Root @ localhost anglea] # echo "I am oldboy teacher welcome to oldboy traning class" | awk '{for (i = 1; i <= NF; i ++) if (length ($ i) <= 6) print $ i } '
I
am
oldboy
to
oldboy
class
Is there a better way to welcome everyone to learn together and share. |
|
|
|