[英]How to delete leading newline in a string in bash?
I'm having the following issue. 我遇到以下问题。 I have an array of numbers: 我有一个数字数组:
text="\n1\t2\t3\t4\t5\n6\t7\t8\t9\t0"
And I'd like to delete the leading newline. 我想删除开头的换行符。 I've tried 我试过了
sed 's/.//' <<< "$text"
cut -c 1- <<< "$text"
and some iterations. 和一些迭代。 But the issue is that both of those delete the first character AFTER EVERY newline. 但是问题在于,这两个命令在每个换行符之后都删除了第一个字符。 Resulting in this: 结果是:
text="\n\t2\t3\t4\t5\n\t7\t8\t9\t0"
This is not what I want and there doesn't seem to be an answer to this case. 这不是我想要的,这种情况似乎没有答案。
Is there a way to tell either of those commands to treat newlines like characters and the entire string as one entity? 有没有办法告诉这两个命令中的任何一个将换行符(例如字符)和整个字符串视为一个实体?
awk
to the rescue! awk
解救!
awk 'NR>1'
of course you can do the same with tail -n +2
or sed 1d
as well. 当然,您也可以对tail -n +2
或sed 1d
做同样的操作。
You can probably use the substitution modifier (see parameter expansion and ANSI C quoting in the Bash manual): 您可能可以使用替换修饰符(请参阅Bash手册中的参数扩展和ANSI C引用 ):
$ text=$'\n1\t2\t3\t4\t5\n6\t7\t8\t9\t0'
$ echo "$text"
1 2 3 4 5
6 7 8 9 0
$ echo "${text/$'\n'/}"
1 2 3 4 5
6 7 8 9 0
$
It replaces the first newline with nothing, as requested. 根据要求,它将用任何内容替换第一条换行符。 However, note that it is not anchored to the first character: 但是,请注意,它没有固定在第一个字符上:
$ alt="${text/$'\n'/}"
$ echo "${alt/$'\n'/}"
1 2 3 4 56 7 8 9 0
$
Using a caret ^
before the newline doesn't help — it just means there's no match. 在换行符之前使用插入符号^
并没有帮助-只是意味着没有匹配项。
As pointed out by rici in the comments , if you read the manual page I referenced, you can find how to anchor the pattern at the start with a #
prefix: 正如rici在评论中所指出的那样,如果您阅读了我参考的手册页,则可以找到如何以#
前缀开头来锚定模式:
$ echo "${text/#$'\n'/}"
1 2 3 4 5
6 7 8 9 0
$ echo "${alt/#$'\n'/}"
1 2 3 4 5
6 7 8 9 0
$
The notation bears no obvious resemblance to other regex systems; 该符号与其他正则表达式系统没有明显的相似之处。 you just have to know it. 您只需要知道它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.