适用于Bash编程初学者小例子 - 第二篇
去掉字符串前面的一个或多个空格。
#!/bin/bash
str="f810yunlong-3: Cache flushing complete. "
IFS=':' read -ra substrs <<< "$str"
NODE="${substrs[0]}"
MSG="${substrs[1]}"
TRIM_MSG= echo "$MSG" | sed -e 's/^[[:space:]]*//'
#Remove the leading spaces from the variable
TRIM_MSG=`echo $MSG | sed -e 's/^[[:space:]]*//'`
# Print the value of $Var after trimming
printf "%s \n" "$NODE"
printf "=%s=\n" "$TRIM_MSG"
判断一个字符串里是否包含有一个子字符串。
#!/bin/bash
str="f810yunlong-3: Cache flushing complete. "
if [[ "$str" == *"Cache flushing complete."* ]]
then
printf "One node cache flushed successfully!\n"
else
printf "[Error] "
printf "Error happened in one node on flushing inline dedupe index and queue flush! \n"
fi
遍历一个文件夹里的所有的zip文件,以各自的zip文件名为各自的目录名,逐个解压到指定的目录下。
#!/bin/sh
ZIPDIR="/ifs/yunlong_bash/dir_zips"
UNZIPDIR="/ifs/yunlong_bash/dir5"
printf "Entered path: $ZIPDIR.\n\n"
cd "$ZIPDIR"
for zip in *.zip
do
dirname=`echo $zip | sed 's/\.zip$//'`
printf "Directory name to extract this file is: %s.\n" $dirname
dirfullpath="$UNZIPDIR/$dirname"
printf "Directory full path to extract this file is:%s.\n" $dirfullpath
mkdir "$dirfullpath"
unzip $zip -d $dirfullpath
printf "\n\n"
done
经过检验成功!
遍历一个文件夹里所有的tar文件,以各自的文件名为目录名,逐个解压到指定的目录下。
#!/bin/sh
TARDIR="/ifs/yunlong_bash/tar_test/tars"
UNTARDIR="/ifs/yunlong_bash/tar_test/untars"
printf "Entered path: $TARDIR.\n\n"
cd "$TARDIR"
for tar in *.tar
do
dirname=`echo $tar | sed 's/\.tar$//'`
printf "Directory name to extract this file is: %s.\n" $dirname
dirfullpath="$UNTARDIR/$dirname"
printf "Directory full path to extract this file is:%s.\n" $dirfullpath
mkdir "$dirfullpath"
tar -xvf $tar -C $dirfullpathprintf "\n\n"
done
经笔者亲自运行检验通过。
终止脚本的进一步执行。
#!/bin/bash
printf "Script is executing."
exit
printf "Script is still executing after exit."
*一试便知,第二句的打印终端上看不到的,因为没被执行。
逐行读取一个文本文件,并将内容输出。
#!/bin/bash
filename="/home/yunlong/source_datasets.txt"
n=1while read line; do
# reading each line
echo "Line No. $n : $line"
n=$((n+1))
done < $filename
参考资料
===========
https://stackoverflow.com/questions/918886/how-do-i-split-a-string-on-a-delimiter-in-bash
https://linuxhint.com/trim_string_bash/
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
2012-07-08 [翻译图书] Moving Applications to the Cloud on the Microsoft Windows Azure Platform - 2
2012-07-08 [翻译图书]-Moving Applications to the Cloud on the Microsoft Windows Azure Platform - 1