zl程序教程

您现在的位置是:首页 >  其它

当前栏目

if[-n] 、tr的用法

用法 if tr
2023-09-14 09:13:32 时间

if [ -n ] 正确使用方法

if [ str1 = str2 ]       当两个串有相同内容、长度时为真 
if [ str1 != str2 ]      当串str1和str2不等时为真 
if [ -n str1 ]       当串的长度大于0时为真(串非空) 
if [ -z str1 ]        当串的长度为0时为真(空串) 
if [ str1 ]         当串str1为非空时为真

shell 中利用 -n 来判定字符串非空。
 

tr命令


1. tr 命令的使用


1.It can be used to perform substitution of characters,deletion of the characters, and squeezing of repeated characters from the standard input.
2.tr accepts input only through stdin (standard input) and cannot accept input through command-line arguments.【tr命令仅仅支持标准输入,不支持参数输入】
3.tr [options] set1 set2【如果set1 和 set2的长度不等,那么就会出现映射不匹配问题。】
4.ROT13 is a well-known encryption algorithm. The ROT13 scheme performs alphabetic rotation of characters for 13 characters.【ROT13 是一个著名的加密算法。字母往后13的字母就是加密后的字符】


如下这个就是使用ROT13作为加密算法使用,同时使用tr命令测试

[root@server4 backup]# echo "tr came, tr saw, tr conquered." | tr 'a-zA-Z' 'n-za-mN-ZA-M'
ge pnzr, ge fnj, ge pbadhrerq.
1
2


将文件file.txt中的内容作为tr命令的输入,然后将其中的空格转换成+

[root@server4 backup]# tr ' ' '+' < file.txt
hello+spark+\n+hello+hadoop
hello+hive
1
2
3


-d 参数


tr has an option -d to delete a set of characters that appear on stdin by using the specified set of characters to be deleted as follows:

$ cat file.txt | tr -d '[set1]'
#Only set1 is used, not set2【只需要使用set1,不需要参数set2】
1
2


将字符串中的指定内容删除

[root@server4 backup]# echo "hello 123 world 456" | tr -d '0-9'
hello  world 
1
2


-c 参数


Here,the complement set is the set containing all numerals,space characters,and newline characters.All other characters are removed since -d is used with tr.
-c参数指定的集合会被保留
 

[root@server4 backup]# echo hello 1 char 2 next 4 | tr -d -c '0-9 \n'
 1  2  4


Here,the complement set is the set containing all numerals,space characters,and newline characters.All other characters are removed since -d is used with tr.
1
2
3


-s 参数
压缩重复的字符。
tr provides the -s option to squeeze repeating characters from the input.
$[ operation ] performs a numeric operation

[root@server4 shells]# cat sum.txt | echo $[ $(tr '\n' '+') 0 ]
15

Difference between 'if -e' and 'if -f'

[ -e FILE ] True if FILE exists.

This will return true for both /etc/hosts and /dev/null and for directories.

[ -f FILE ] True if FILE exists and is a regular file.

This will return true for /etc/hosts and false for /dev/null (because it is not a regular file), and false for /dev since it is a directory.