[linux]linux过滤日志奇偶数行

sed -n -e 'n' -e 'p' -i tmp.txt 偶数 实践过

去掉文件里的重复行:
sort file |uniq

下面就把这些方法总结下来。
along@along-laptop:~/code/shell$ cat file
1
2
3
4
5
6
7

awk实现:

一:
1,awk 'NR%2==1' file
2,awk 'NR%2==0' file

二:(这是直接将偶数行和奇数行分别打印到了file2和file1中,这种方法有缺陷就是在file2中始终会打印
最后一行,这个应该改进。不过这也是一种思想,我就把这种方法放在这里了。)
awk '{print $0 > "file1"; getline; print $0 > "file2"; }' file

三:
1.awk 'NR%2' file
2.awk '!(NR%2)' file

四:
1.awk 'i=i?0:1' file
2.awk '!(i=i?0:1)' file

五:
1.awk 'i=!i' file
2.awk '!(i=!i)' file

解释:
awk 'var=xx'应该说等价于awk 'xx{print}{var=xx}'

awk 'i=!i' == > awk '!i{print}{i=!i}
line 1: !0{print}{i=!0}==> {print;i=1}
line 2: !1{print}{i=!1}==> {i=0}
line 3: !0{print}{i=!0}==> {print;i=1}
sed实现

一:
1.sed -n 'p;n' file
2.sed -n 'n;p' file

二:(这种方法更通用一点)
1.sed -n '1~2p' file
2.sed -n '2~2p' file

关于sed的模式空间的问题以及G,g,H,h的问题可以在我的另外一篇文章中找到我的总结。
http://blog.chinaunix.net/u2/77727/showart.php?id=1997477
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用 POSIX 线程库实现的 Linux 双线程交替打印偶数的示例代码: ```c #include <stdio.h> #include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // 初始化互斥锁 pthread_cond_t cond = PTHREAD_COND_INITIALIZER; // 初始化条件变量 int count = 0; // 打印计数器 void *print_even(void *arg) { while (count <= 10) { pthread_mutex_lock(&mutex); // 加锁 if (count % 2 == 0) { // 判断是否为偶数 printf("even thread: %d\n", count); count++; pthread_cond_signal(&cond); // 发送信号 } else { pthread_cond_wait(&cond, &mutex); // 等待信号 } pthread_mutex_unlock(&mutex); // 解锁 } pthread_exit(NULL); } void *print_odd(void *arg) { while (count <= 10) { pthread_mutex_lock(&mutex); // 加锁 if (count % 2 == 1) { // 判断是否为数 printf("odd thread: %d\n", count); count++; pthread_cond_signal(&cond); // 发送信号 } else { pthread_cond_wait(&cond, &mutex); // 等待信号 } pthread_mutex_unlock(&mutex); // 解锁 } pthread_exit(NULL); } int main() { pthread_t tid1, tid2; pthread_create(&tid1, NULL, print_even, NULL); // 创建偶数线程 pthread_create(&tid2, NULL, print_odd, NULL); // 创建数线程 pthread_join(tid1, NULL); // 等待线程结束 pthread_join(tid2, NULL); pthread_mutex_destroy(&mutex); // 销毁互斥锁 pthread_cond_destroy(&cond); // 销毁条件变量 return 0; } ``` 上述代码中,我们使用了互斥锁和条件变量来实现线程间的同步和通信。其中,互斥锁用来保护打印计数器 `count` 的访问,条件变量用来等待和发送信号。在偶数线程中,如果当前的 `count` 为偶数,则打印并将 `count` 加 1,并发送信号通知数线程;否则等待数线程发送信号。在数线程中,如果当前的 `count` 为数,则打印并将 `count` 加 1,并发送信号通知偶数线程;否则等待偶数线程发送信号。最后,我们使用 `pthread_join` 函数等待两个线程结束,并销毁互斥锁和条件变量。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值