我有一些文本在所有行上都有一些前导空格.我想从最短的行中删除空格(如果它更简单,可以将此要求更改为第一行),然后从所有其他行中删除相同数量的空格.
我有这样的文字:
var flatten = function(result, next_array) {
console.log('current result', result);
return result.concat(next_array);
};
[1, [2], [3, 4]]
.reduce(flatten, []);
Run Code Online (Sandbox Code Playgroud)
我希望得到这样的文字:
var flatten = function(result, next_array) {
console.log('current result', result);
return result.concat(next_array);
};
[1, [2], [3, 4]]
.reduce(flatten, []);
Run Code Online (Sandbox Code Playgroud)
基本上,我想将文本移动到左边至少有一行没有空格,并保留所有其他行上的所有其他前导空格.
用例是将代码段中间的代码复制到其他地方作为示例粘贴.我目前所做的是复制代码,使用粘贴插入模式粘贴到vim ,使用<<直到我得到所需的输出,然后复制缓冲区.使用Cmd- 可以在TextMate中完成相同的操作[.
我想要的是使用shell脚本执行此操作,以便我可以使用热键触发它以获取剪贴板内容,删除所需的空格并粘贴结果.
这个 awk one-liner 也可以为你做到这一点。它假设您要删除至少 1 个空格。(因为我在您的示例中看到,有一个空行,没有任何前导空格,但无论如何所有行都会向左移动。)
用你的例子进行测试:
kent$ cat f
var flatten = function(result, next_array) {
console.log('current result', result);
return result.concat(next_array);
};
[1, [2], [3, 4]]
.reduce(flatten, []);
kent$ awk -F '\\S.*' '{l=length($1);if(l>0){if(NR==1)s=l; else s=s>l?l:s;}a[NR]=$0}END{for(i=1;i<=NR;i++){sub("^ {"s"}","",a[i]);print a[i]}}' f
var flatten = function(result, next_array) {
console.log('current result', result);
return result.concat(next_array);
};
[1, [2], [3, 4]]
.reduce(flatten, []);
Run Code Online (Sandbox Code Playgroud)
编辑
我不认为 awk 脚本不可读。但你必须知道 awk 脚本的语法。无论如何,我添加一些解释:
awk 脚本有两个块,第一个块在读取文件的每一行时执行。该END块是在读取文件的最后一行后执行的。请参阅下面的注释以获取解释。
awk -F '\\S.*' #using a delimiter '\\S.*'(regex). the first non-empty char till the end of line
#so that each line was separated into two fields,
#the field1: leading spaces
#and the field2: the rest texts
'{ #block 1
l=length($1); #get the length of field1($1), which is the leading spaces, save to l
if(l>0){ #if l >0
if(NR==1)s=l; #NR is the line number, if it was the first line, s was not set yet, then let s=l
else s=s>l?l:s;} #else if l<s, let s=l otherwise keep s value
a[NR]=$0 #after reading each line, save the line in a array with lineNo. as index
} #this block is just for get the number of "shortest" leading spaces, in s
END{for(i=1;i<=NR;i++){ #loop from lineNo 1-last from the array a
sub("^ {"s"}","",a[i]); #replace s number of leading spaces with empty
print a[i]} #print the array element (after replacement)
}' file #file is the input file
Run Code Online (Sandbox Code Playgroud)