牛客Shell实战题目1~8
Posted xingweikun
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了牛客Shell实战题目1~8相关的知识,希望对你有一定的参考价值。
文章目录
SHELL1 统计文件的行数
描述
写一个 bash脚本以输出一个文本文件 nowcoder.txt中的行数
示例:
假设 nowcoder.txt 内容如下:
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int b = 100;
cout << "a + b:" << a + b << endl;
return 0;
}
你的脚本应当输出:
9
#!/bin/bash
line=0
while read p
do
((line++))
done < nowcoder.txt
echo $line
其他方法
wc -l < nowcoder.txt
grep -c "" nowcoder.txt
awk 'END{print NR}' nowcoder.txt
sed -n '$=' nowcoder.txt
SHELL2 打印文件的最后5行
#!/bin/bash
while read line
do
row=$((row+1))
done<nowcoder.txt
while read line
do
if [ $row -lt 6 -a $row -gt 0 ]
then
echo $line
fi
row=$((row-1))
done<nowcoder.txt
其他方法
tail -n 5 nowcoder.txt
SHELL3 输出7的倍数
#!/bin/bash
for num in {0..500..7}
do
echo "$num"
done
#!/bin/bash
for((num=0;num<=500;num=num+7))
do
echo "$num"
done
SHELL4 输出第5行的内容
#!/bin/bash
line=1
while read value
do
if [ $line -eq 5 ]
then
echo $value
fi
((line++))
done < nowcoder.txt
sed -n "5p" nowcoder.txt
head -n 5 nowcoder.txt | tail -n 1
awk -F : 'NR==5 {print $0}' nowcoder.txt
SHELL5 打印空行的行号
描述
写一个 bash脚本以输出一个文本文件 nowcoder.txt中空行的行号,可能连续,从1开始
示例:
假设 nowcoder.txt 内容如下:
a
b
c
d
e
f
你的脚本应当输出:
3
5
7
9
10
#!/bin/bash
row=0
while read line
do
((row++))
#if [ -z $line ];then
#if [ ! $line ];then
if [ "$line" = "" ];then
echo $row
fi
done < nowcoder.txt
其他方法
正则匹配空行 \\s(匹配任何空白字符:包括空格,制表符,换页符等等.等价于[ \\f\\n\\r\\t\\v])且输出带行号.
在^
符号前面加/
是因为^
是特殊符号,需要转义.
awk '/^\\s*$/{print NR}' nowcoder.txt
sed -n '/^\\s*$/=' nowcoder.txt
SHELL6 去掉空行
#!/bin/bash
row=0
while read line;
do
if [ ! -z $line ];then
echo $line
fi
done
exit
其他方法
awk '{if($0 != ""){print $0}}' nowcoder.txt
cat nowcoder.txt | awk NF
-v
显示不包含匹配文本的所有行
grep -v '^$' nowcoder.txt
-e
指定字符串做为查找文件内容的样式
grep -e '\\S' nowcoder.txt
SHELL7 打印字母数小于8的单词
#!/bin/bash
read line < nowcoder.txt
for n in $line
do
if [ "${#n}" -lt 8 ]
then
echo "${n}"
fi
done
SHELL8 统计所有进程占用内存大小的和
描述
假设 nowcoder.txt 内容如下:
root 2 0.0 0.0 0 0 ? S 9月25 0:00 [kthreadd]
root 4 0.0 0.0 0 0 ? I< 9月25 0:00 [kworker/0:0H]
web 1638 1.8 1.8 6311352 612400 ? Sl 10月16 21:52 test
web 1639 2.0 1.8 6311352 612401 ? Sl 10月16 21:52 test
tangmiao-pc 5336 0.0 1.4 9100240 238544 ?? S 3:09下午 0:31.70 /Applications
以上内容是通过ps aux | grep -v 'RSS TTY'
命令输出到nowcoder.txt
文件下面的
请你写一个脚本计算一下所有进程占用内存大小的和:
awk '{sum+=$6}END{print sum}' nowcoder.txt
sum=0
while read -a a
do
sum=$(($sum+${a[5]}))
done<nowcoder.txt
echo $sum
以上是关于牛客Shell实战题目1~8的主要内容,如果未能解决你的问题,请参考以下文章