微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

linux shell之字符串的更具字符分割和删除字符和文本内容的删除以及内容是否匹配成功

1  字符串的更具字符分割

1) xargs分割

echo "chenyu*hello*word" | xargs -d "*"
chenyu hello word

 

2) awk分割

echo "chenyu*hello*word" | awk -F "*" '{print $1}'
chenyu

 

 

 

 

 

2 字符串的删除字符

1)用tr命令

echo "chenyu ni hao ya" | tr -d 'y' 
chenu ni hao a

2)用sed命令

echo  "hello*word*word" | sed 's/*//g'
hellowordword

 

 

 

 

 

 

 

 

3 文本内容删除

用sed命令

cat 1.txt
chenyu
nihao
hello
word
chenyu
nihao
dongma
sed -i '/chenyu/d' 1.txt
cat 1.txt
nihao
hello
word
nihao
dongma

 

 

 

 

 

 

 

 

 

 

4 grep -q 用于if逻辑判断

-q 参数,本意是 Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found,even if an error was detected.  中文意思为,安静模式,不打印任何标准输出。如果有匹配的内容则立即返回状态值0

自己测试如下

#/bin/bash

value="chenyu ni hao ya"

#匹配成功执行$?返回0
echo "hello" | grep -q "he";
echo $?
#匹配失败执行$?非0
echo "hello" | grep -q "hehelodaf";
echo $?

#如果能匹配成功那么就到then反之到else
if echo $value | grep -q "chenyuddsa"; 
then
   echo "first success" 
else
   echo "first fail"
fi


if echo $value | grep -q "hao"; 
then
   echo "second success" 
else
   echo "second fail"
fi

允许结果如下:

./grep.sh
0
1
first fail
second success

 

 

 

 

 

 

 

5 grep -i(忽略大小写)来判断结果

#/bin/bash

value="chenyu"
echo $value | grep -i "chen" > /dev/null

if [ $? -eq 0 ];
then
	echo "grep success"
else
	echo "grep fail"
fi

echo $value | grep -i "chengongyu" > /dev/null

if [ $? -eq 0 ];
then
	echo "grep success"
else
	echo "grep fail"
fi




运行结果

grep success
grep fail

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。