正则表达式问题在整个文件夹中查找尾随空格

发布于 2024-07-19 04:15:08 字数 194 浏览 3 评论 0原文

我有一个从 WordPress 安装中提取的文件夹,其中有超过 1000 个文件。 一些 php 代码由于最后一行上的尾随空格而引发错误(我清理了页面最后几行上的 iframe 注入,并确实查找/替换为空格,但不知道这会抛出所有错误)我的代码)。

削减这些空间的最有效方法是什么? 我以前从未运行过正则表达式,但知道这就是我会使用的。 帮助!

I have a folder pulled from a wordpress installation, >1000 files. Some php code is throwing an error due to trailing spaces on the very last line (I cleaned up an iframe injection on some final lines of pages, and did find/replace with a space, but didn't know that that would throw off all my code).

What's the most efficient way to chop those spaces? I've never run a regex before, but know that's what I would use. Help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

护你周全 2024-07-26 04:15:08

类似于:

find -type f |xargs sed -i '$s/[[:space:]]+$//'

这应该删除 cwd 中任何文件的最后一行上的尾随空格。 第一个 $ 是“最后一行”的 sed 地址,第二个是行尾的正则表达式。

与往常一样,请务必先备份。

Something like:

find -type f |xargs sed -i '$s/[[:space:]]+$//'

That should remove trailing spaces on the last line of any file anywhere within the cwd. The first $ is the sed address for "last line" and the second is the regex for end of line.

As always, be sure to backup first.

茶花眉 2024-07-26 04:15:08

如果您确定它是文件最后一行的尾随空格,那么您需要一个 bash 脚本(我假设您使用的是 Linux)来为每个文件(使用“find .”来获取list),tail -1 文件,然后 grep 该行查找空格或制表符。

切线而言,知道结束语 ?> 是有用的。 PHP 文件末尾是不必要的,最好将其省略。 我无法计算有多少次看到以“?>”结尾的 PHP 文件,人们疯狂地试图找到导致输出/标头问题的一个额外空格。

If you're certain it's a trailing space on the last line of the file, then you'd want a bash script (I'm assuming you're using Linux) to, for each file (use "find ." to get a list), tail -1 the file, and then grep that line for space or tab.

Tangentially, it's useful to know that the closing ?> is unnecessary at the end of PHP files, and it's best to omit it there. I can't count the number of times I've seen a PHP file that ends with "?> " and people go nuts trying to find that one extra space that's causing output/header problems.

山人契 2024-07-26 04:15:08

在这种情况下,我要做的就是编写一个脚本或程序,当给定一个目录时,它会递归地查找以 .php 或其他结尾的文件,然后只需编写一个函数
1)查找最后一个字节并存储该位置
2)如果该字节是空白,则查找一个字节并再次检查
3)如果不是空白,则返回偏移量,

然后使用该偏移量,您可以将每个文件写为新副本或覆盖旧副本

P.S 上述解决方案之一也可以工作:P

in this case what i would do is write a script or program that when given a directory it recursively goes through finding files ending in .php or whatever then simply write a function that
1)seeks to the last byte and stores this position
2)if this byte is whitespace seek back a byte and check again
3)if it is not white space return the offset

then using that you can either write out each file as a new copy or over the old one

P.S one of the above solutions would also work :P

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文