file.txt
用来实验的文本文件
how they are implemented and applied in computer
that is your bag
is this your bag?
to the degree or extent indicated.
there was a court case resulting from this incident
welcome to nowcoder
welcome nowcoder
welcome to nowcoder
nowcoder
how they are implemented and applied in computer
that is your bag
is this your bag?
to the degree or extent indicated.
there was a court case resulting from this incident
welcome to nowcoder
welcome nowcoder
1
welcome to nowcoder
nowcoder
test.sh
测试程序,通过实验文本完成七个需求
#!/bin/bash
echo "requir-1: 统计文件中的行数"
cat file.txt | wc -l # wc -l 会打印文件中文本的行数,基数从0开始起。
echo
echo "requir-2: 打印前8行"
head -n 8 file.txt # equal to: head -n +8 file.txt
echo externalInfo
head -n -8 file.txt # 从最后的非空行开始数,打印倒数第八行~开头的所有行
echo
echo "requir-3: 打印后8行"
tail -n 8 file.txt # equal to: tail -n -8 file.txt
echo externalInfo
tail -n +8 file.txt # 从第八行开始,一直打印到末尾行
echo
echo "requir-4: 打印第11行"
sed -n '5p' file.txt
echo external
awk 'NR==5' file.txt
echo externalCombine
head -n 5 file.txt | tail 1
echo
echo "requir-5: 打印空行的行号"
awk '/^$/{print NR}' file.txt
# /xxx/是转义符的意思?或者是指要搜索的内容
# 搜索包含^$的行,打印出所在的行号。个人猜测:^$是以$为开头的行,$可能代表换行符,以换行符为开头的行,就是空行。
echo
echo "requir-6: 去掉空行"
sed -i '/^$/d' file.txt # /xx/d: 删除指定的内容,d是删除;^$是空行,-i代表对文件做出修改
echo
echo "requir-7:将文本中的每一行,以字段顺序进行逆转输出"
awk -F " " ' # 设置分隔符,分割为空格" "
{
s=""; # awk会逐次将文本的每一行内容作为输入,s为每一行的起始数据
for(i=NF;i>=1;i--){ # NF表示awk的字段个数,$NF则表示字段最后一个列
if(i==NF) s=$i; # 末尾字段作为起始 $i 就是各个字段的内容
else s=s" "$i; # 之后逐个添加字段
}
print s # 这里仅仅将字段打印出来,有需要的话可以直接写入到文件中
}
' file.txt
echo