如何修剪文本文件的内容?

Law*_*nce 5 linux sed text-processing whitespace

我想从文本文件的开头和结尾删除所有“空白”字符,包括 \n(如果存在)。(基本上模仿大多数编程语言的 trim() 函数的行为,如果“文件”是一个大字符串)。

αғs*_*нιη 2

使用sed

sed -z 's/^\s*//; s/\s*$//' infile
Run Code Online (Sandbox Code Playgroud)
  • s/^\s*//infile,在作为输入文件时删除空格/空行。

  • s/\s*$//infile,删除了作为输入文件最末尾的空格/空行,\n包括infile.

例子cat -e infile

$
$
$
Three blank lines above$
$
$
Two blank lines in the middle$
a blank lines below$
$
a line with trailing whitespaces                $
          a line with leading whitespaces$
below are two empty lines + one whitespaces then an empty line again$
$
$
                                    $
$
Run Code Online (Sandbox Code Playgroud)

输出:

Three blank lines above


Two blank lines in the middle
a blank lines below

a line with trailing whitespaces
          a line with leading whitespaces
below are two empty lines + one whitespaces then an empty line again
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用printf打印删除第一个空格/空行的结果sed,并在仅在最后删除空行的命令替换中使用它\n

printf '%s' "$(sed -z 's/^\s*//' infile)"
Run Code Online (Sandbox Code Playgroud)