linux - 使用 grep/sed 仅在文件末尾递归删除尾随空格?

标签 linux bash shell unix scripting

基本上,我有大约 1,500 个文件,这些文件的最后一个字符不应该是任何类型的空格。

如何检查一堆文件以确保它们没有以某种形式的空格结尾?(换行符、空格、回车符、制表符等)?

最佳答案

awk '{if (flag) print line; line = $0; flag = 1} END {gsub("[[:space:]]+$","",line); printf line}'

编辑:

新版本:

sed 命令删除所有仅包含空格的尾随行,然后 awk 命令删除结尾的换行符。

sed '/^[[:space:]]*$/{:a;$d;N;/\n[[:space:]]*$/ba}' inputfile |
    awk '{if (flag) print line; line = $0; flag = 1} END {printf line}'

缺点是读取文件两次。

编辑 2:

这是一个只读取文件一次的全 awk 解决方案。它以类似于上面的 sed 命令的方式累积纯空白行。

#!/usr/bin/awk -f

# accumulate a run of white-space-only lines so they can be printed or discarded
/^[[:space:]]*$/ {
    accumlines = accumlines nl $0
    nl = "\n"
    accum = 1
    next
}

# print the previous line and any accumulated lines, store the current line for the next pass
{
    if (flag) print line
    if (accum) { print accumlines; accum = 0 }
    accumlines = nl = ""
    line = $0
    flag = 1
}

# print the last line without a trailing newline after removing all trailing whitespace
# the resulting output could be null (nothing rather than 0x00)
# note that we're not print the accumulated lines since they're part of the 
# trailing white-space we're trying to get rid of
END {
    gsub("[[:space:]]+$","",line)
    printf line
}

编辑 3:

  • 删除了不必要的 BEGIN 子句
  • lines 更改为 accumlines,以便更容易与 line(单数)区分开来
  • 添加评论

关于linux - 使用 grep/sed 仅在文件末尾递归删除尾随空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4727268/

相关文章:

android - VALGRIND 内部错误 : Valgrind received a signal 11 (SIGSEGV) - exiting

python - 在目录中查找最旧的文件(递归)

bash - 如何使用 sed 用\(space) 替换空格?

linux - 从 .bashrc 中键/值对的 .list 文件设置环境变量

c - OpenGL 头文件版本信息不匹配

c - 如何使用 Unix 系统调用打印文本文件的前 10 行?

bash - CD $PATH : No such file or directory

linux - BASH:自动完成 printf "%s"的 $keyword

python - postgres 找到所有者为 'abc' 的所有数据库?

linux - 使用 grep 在线匹配模式