Well, let me first explain that in Bash a set of words separated by one or more space characters is a very common thing because it is very easy to split and work with it. Thus, there are very little cases where you could need to remove all the space characters.
However, here is a little and simple example of how could you do that:
$ echo "a b c d" | sed 's/ //g' abcd
Simple enough, eh?
If the text to be modified is already stored in a variabile you can even use bashparameter substitution:
$ string="a b c d"
$ echo ${string// /}
abcd
Quite better!
And what if we want to remove newline characters?
The answer unfortunately is not that easy seeing that:
$ echo -e "a b c/nd e f" | sed 's//n//g' a b c d e f
doesn’t bring to the desired result. In fact, if we want to remove newline characters from a string we need to manually place each line into the pattern space and then remove the wanted element; here is how we can do it:
$ echo -e "a/nb/nc/nd/ne/nf" | sed '/^.*$/N;s//n//g' ab cd ef
This is not yet the final result: only one newline every two is removed.
Here is how it works:
- /^.*$/matches all the strings composed by zero or more of any character (.*) and starting/ending with the line
- /Nstore the matched string to the pattern space and get the next
- s/substitute
- /n/newline character
- //with nothing
- /gglobally
The final solution for newline characters removal is:
$ echo -e "a/nb/nc/nd/ne/nf" | sed ':start /^.*$/N;s//n//g; t start'
which involvesspaghetti code(start is a label andt startis just a goto).
If the input is a file there is nicer way:
#!/bin/bash result=""; while read line; do result="$result $line"; done < myfile
PS:
echo -e "a/nb/nc/nd/ne/nf" | tr -d "/n"
does the trick also
本文介绍了如何使用Bash脚本中的sed和tr命令来去除字符串中的空格和换行符。通过实例展示了直接处理字符串及从文件中读取内容的方法。
3万+

被折叠的 条评论
为什么被折叠?



