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
(0)

相关推荐