如何使用php从文件中删除行(记录)
我想删除行尾具有唯一 id 的行。如何删除该行? php 中有 sed 或 awk 的实现吗?我的文件结构如下
1 0 * * * echo -n "cron 1" > /www/apache/logs/error_log #1 0 */2 * * * /home/user/test1.pl #2 1 0 * * * echo -n "cron 2" > /www/apache/logs/error_log #3 0 */2 * * * /home/user/test2.pl #4 1 0 * * * echo -n "cron 3" > /www/apache/logs/error_log #5 0 */2 * * * /home/user/test3.pl #6
在上面的示例中,唯一 id 位于每行末尾,带有“#”,后跟整数 id 值。如何通过唯一键标识来删除一行?谢谢。
I want to delete a line which has unique id at the end of the line. how to delete the line? Is there any implementation of sed or awk in php? my file structure is as follows
1 0 * * * echo -n "cron 1" > /www/apache/logs/error_log #1 0 */2 * * * /home/user/test1.pl #2 1 0 * * * echo -n "cron 2" > /www/apache/logs/error_log #3 0 */2 * * * /home/user/test2.pl #4 1 0 * * * echo -n "cron 3" > /www/apache/logs/error_log #5 0 */2 * * * /home/user/test3.pl #6
in the above example unique id is at the end of each line with "#" followed by the integer id value. How to delete a line by identifying with its unique key? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 PHP 中使用 awk(例如删除 #4 行)
,您可以迭代文件并使用正则表达式查找 id:
"#\d+$"
,或者您可以在空格上拆分行并检查最后一个元素不是您指定的 uniq 编号。with awk, (eg deleting #4 line )
in PHP, you can iterate the file and look for the id with regex :
"#\d+$"
, or you can split the line on whitespace and check that the last element is not the uniq number you specified.有点像
Smth like
使用
grep
:grep -v '#3$' filename
使用
sed
:sed -e '/#3$/d' filename
仅删除末尾带有
#3
的行。With
grep
:grep -v '#3$' filename
With
sed
:sed -e '/#3$/d' filename
to remove only the line with a
#3
at its end.裸 PHP 就可以了。
Bare PHP will do.