需求
在做关键词清洗过程中,需要将一类不符合某个字结尾的词过滤出来,思路是把这一批词按最后一个字排序,于是想到了先把这些词反转一下,如把12345转为54321,好像以前在夜息的文章里看过用shell可以实现,就百度了一下,找到几个可行的解决,现记录一下。
shell实现字符串反转,一句命令搞定!
cat keywords.txt|while read line;do echo $line|rev;done
命令的:
echo 12345|rev
54321
python 的:
echo 12345|python -c 'print raw_input()[::-1]'
sed 的:
echo 12345|sed '/\n/!G;s/\(.\)\(.*\n\)/&\2\1/;//D;s/.//'
awk 的:
echo 12345|awk 'BEGIN{FS=""}{for(a=NF;a>0;a--)printf("%s",a==1?$a"\n":$a)}'
纯 bash 的:
echo 12345|{ read;for((i=${#REPLY};i>0;i--))do echo -n "${REPLY:$[i-1]:1}";done;echo; };
c 的:
gcc -o a -O2 -x c <(cat <<!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc,char *argv[])
{
if(argc != 2)
{
printf("%s reverse lines of a string\n",argv[0]);
exit(1);
}
int i=0;
char *p;
p=argv[1];
i=strlen(argv[1])-1;
for(i;i>=0;i--)
{
printf("%s%s",&p[i],(i==0)?"\n":"");
p[i]='\0';
}
})&& ./a "12345" ;rm -f a
参考网站:http://bbs.chinaunix.net/thread-1729795-1-1.html

评论