首页 > 系统相关 >shell判断字符串结尾

shell判断字符串结尾

时间:2023-03-25 13:34:34浏览次数:48  
标签:shell false 结尾 echo str foo 字符串 txt true

下面围绕“判断字符串是否以.txt结尾”展开。转变一下也同样适用于“判断字符串是否以.txt开头”。

通用的方法

# 方法一、使用grep命令

#!/bin/sh

str="/path/to/foo.txt"

# 使用if语句
if echo "$str" | grep -q -E '\.txt$'
then
	echo "true"
else
	echo "false"
fi

# 写成一行
echo "$str" | grep -q -E '\.txt$' && echo true || echo false
grep -q -E '\.txt$' <<< "$str" && echo true || echo false

# 方法二、使用expr命令

#!/bin/sh

str="/path/to/foo.txt"

# 使用if语句
if expr "$str" : '.*\.txt$' &>/dev/null
then
	echo "true"
else
	echo "false"
fi

# 写成一行
expr "$str" : '.*\.txt$' &>/dev/null && echo true || echo false

# 方法三、使用case指令

#!/bin/sh

str="/path/to/foo.txt"

case "$str" in
	*.txt ) echo "true";;
	* ) echo "false";;
esac

# 其他方法

还可以使用AWK、SED,这里就不再介绍了,方法和上面是类似的。

特定于Shell的方法

BASH

#!/bin/bash

# BASH中的正则表达式
[[ "/path/to/foo.txt" =~ .*txt$ ]] && echo "true" || echo "false"

# BASH的特殊语法
[[ "/path/to/foo.txt" = *txt ]] && echo "true" || echo "false"

相关文章

「Shell」- 在脚本中,获取脚本所在路径
「Sehll」- 重复字符串

参考文献

How do I do if(string.endsWith("/")) in shell
Bash String Comparison: Find Out IF a Variable Contains a Substring

 

标签:shell,false,结尾,echo,str,foo,字符串,txt,true
From: https://www.cnblogs.com/exmyth/p/17254583.html

相关文章

  • BASH: disable shell builtin
     enable      Usethe`env`command.Envisacommandwhichlaunchesanotherprogramwithapossiblymodifiedenvironment.Becauseenvisapro......
  • 实验2 字符串和列表
    实验任务1task.py实验源码:x='nbaFIFA'print(x.upper())print(x.lower())print(x.swapcase())print()x='abc'print(x.center(10,'*'))print(x.ljust(1......
  • 优美字符串
    0036:优美字符串查看提交统计提问总时间限制: 1000ms 内存限制: 65536kB描述对于给定的两个字符串,我们将要做的是将它们拼接起来,拼接成一个“优美”的字符串,那么什么样的......
  • 代码随想录Day9-Leetcode28. 实现 strStr(),459.重复的子字符串
    28.实现strStr()这题之前写过,而且印象深刻的是细节很多,所以这边是看完以前的代码,再写的(几乎是在背代码了hhh)甚至这样,next[0]=-1,和j开始匹配子串是没初始化成......
  • java-使用jmh基准测试框架比较五种字符串拼接性能
    java-使用jmh基准测试框架比较五种字符串拼接性能引言Java中提供了5种字符串拼接的方法,使用+拼接字符串是最长见的方法。除此还有StringBuilder、StringBuffer、MessageForm......
  • 实验2 字符串和列表
    实验二字符串和列表实验任务1task1.py实验源码x='nbaFIFA'print(x.upper())print(x.lower())print(x.swapcase())print()x='abc'print(x.center(10,'*'))......
  • Python字符串_拼接+还是join
    常用的join方法用来将列表或元祖中包含的多个字符串连接成一个字符串newstr = str.join(iterable)  newstr:表示合并后生成的新字符串; str:用于指定合并时的分隔......
  • shell编程-FTP服务账号的批量设置
    FTP账号配置:应用背景:安装vsftpd服务程序:echo“HELLOhello”>/ftproot/bjtt/a.txt是目录权限导致:OOPS错误验证bjtt_upload的权限:验证bjtt_download的权限:脚本实现:......
  • c语言部分系统调用函数(shell编程)
    头文件<fcntl.h>文件控制<unistd.h>符号常量<sys/stat.h>文件状态<sys/types.h>基本系统数据类型<utime.h>文件时间<dirent.h>目......
  • 代码随想录Day8-Leetcode344.反转字符串 II,541. 反转字符串II ,剑指Offer 05.替换空格
    344.反转字符串题目链接:https://leetcode.cn/problems/reverse-string明显的双指针/***@param{character[]}s*@return{void}Donotreturnanything,modif......