Shell腳本學習——字符串處理

最近在做很多的字符串處理的工作,主要用的還是excel,但是很費神,總是Ctrl+C和Ctrl+V。就想用shell腳本對對應的字符串進行批量處理。

Shell腳本學習——字符串處理

1)首先是讀取文件中的每一行字符串

使用cat和while來讀取file文件中的每一行,並輸出到target文件中。

 cat $file | while read LINE
do
echo $LINE >> $target
done

2)判斷字符串是否含有特定的字符

"=~"正則式匹配符號,"_"就是要匹配的對象,也可使替換為其他的符號。

 if [[ $LINE =~ "_" ]]; then
echo "It contains the '_'"
else
echo "It does not contains the '_'"
fi

2)替換"_"字符

使用sed命令刪除"_"。

sed -i 's/_//g' $target

3)首字母大寫

找到每行的首字母^\\w和"_"之後的首字母\\_\\w,然後替換為大寫字母\\U&。

\\w 相當於 [a-zA-Z0-9] 。\\U將後面的字符轉換成大寫,&指前面匹配的內容,下面sed的作用是將行首字母或者是_後面每個單詞的首字母轉換成大寫。

sed -i 's/^\\w\\|\\_\\w/\\U&/g' $target

4)判斷只有數字的行

 if [ -n "$(echo $LINE | sed -n "/^[0-9]\\+$/p")" ]; then
ehco "This line is number"
fi

5)字符串轉換為小寫

注意tr之後的'A-Z'和'a-z'有空格。

echo $LINE | tr 'A-Z' 'a-z'

下面是我編寫的腳本,與大家共享,歡迎大家拍磚。

 cat $file | while read LINE
do
if [ -n "$(echo $LINE | sed -n "/^[0-9]\\+$/p")" ]; then
echo "~~~~~~~~~~~$LINE~~~~~~~~~~~~" >> $target
else
if [[ $LINE =~ "_" ]]; then
lowercase=$(echo $LINE | tr 'A-Z' 'a-z')
else
lowercase=$LINE
fi
echo ${lowercase}HelpId >> $target
sed -i 's/^\\w\\|\\_\\w/\\U&/g' $target
sed -i 's/\\s\\w/\\U&/g' $target
sed -i 's/_//g' $target
fi
done


分享到:


相關文章: