如何在bash脚本中的特殊字符后添加空格?
我有一个文本文件,其中包含
!aa
@bb
#cc
$dd
%ee
预期输出,
! aa
@ bb
# cc
$ dd
% ee
我尝试过的内容,echo "${foo//@/@ }"
。
这对于一个字符串确实可以正常工作,但不适用于文件中的所有行。我尝试使用这个 while 循环来读取文件的所有行并使用 echo 执行相同的操作,但它不起作用。
while IFS= read -r line; do
foo=$line
sep="!@#$%"
echo "${foo//$sep/$sep }"
done < $1
我尝试过 awk split 但它没有给出预期的输出。有什么解决方法吗?通过使用 awk 或 sed。
I have a text file with something like,
!aa
@bb
#cc
$dd
%ee
expected output is,
! aa
@ bb
# cc
$ dd
% ee
What I have tried, echo "${foo//@/@ }"
.
This does work fine with one string but it does not work for all the lines in the file. I have tried with this while loop to read all the lines of the file and do the same using echo but it does not work.
while IFS= read -r line; do
foo=$line
sep="!@#$%"
echo "${foo//$sep/$sep }"
done < $1
I have tried with awk split but it does not give the expected output. Is there any workaround for this? by using awk or sed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
以下假设您要在
!@#$%
集中的每个字符后面添加一个空格(即使它是一行中的最后一个字符)。测试文件:使用
sed
:使用
awk
:使用普通
bash
(不推荐,太慢):或者(不确定哪个是最差):
The following assumes you want to add a space after every character in the
!@#$%
set (even if it is the last character in a line). Test file:With
sed
:With
awk
:With plain
bash
(not recommended, it is too slow):Or (not sure which is the worst):
在您的示例中,您称为 special 的字符似乎是 GNU
sed
中称为[[:punct:]]
的字符子集,因此我建议以下解决方案:file.txt
内容输出
说明:我使用捕获组
\(
...\)
,其中包含任何属于的字符到[:punct:]
然后我替换捕获的内容捕获的内容后跟空格。我使用g
将其应用于每行中的所有事件,尽管这对上面的数据没有明显的影响。如果您确定每一行中最多有一个字符需要替换,您可以选择删除g
。如果您想了解有关
[:punct:]
或其他类似字符集的更多信息,请阅读 Regular-Expressions.info 上的字符类Characters you call special in your example seems to be subset of characters known as
[[:punct:]]
to GNUsed
, thus I propose following solution:which with
file.txt
content beingoutput
Explanation: I use capturing group
\(
...\)
which has any character belonging to[:punct:]
then I replace what was captured with content of that capture followed by space. I useg
to apply it to all occurences in each line, though this has not visible impact for data above. You might elect to dropg
if you are sure there will be at most one character to replace in every line.If you want to know more about
[:punct:]
or other similar character sets read about Character Classes on Regular-Expressions.info如果文件总是在行开头包含这样的符号,则使用此
-E
选项是告诉sed
使用正则表达式。-i
内联修改文件,如果要输出到控制台或其他文件,可以将其删除。^(.)
正则表达式捕获该行的第一个字符并为其添加一个空格 (\1
)If the file always contain a symbol at the start of line like that then use this
The
-E
option is to tellsed
to use regex.-i
modifies the file inline, you can remove it if you want to output to console or another file. The^(.)
regex captures the first character on the line and add a space to it (\1
)假设
特殊字符
是非数字和非字母字符,并且特殊字符可以出现在行中的任何位置
,请使用以下正则表达式来替换它们。Assuming that
special characters
are non-numeric and non-alphabetic characters, and special characters can appearanywhere
in the line, use the following regular expression to replace them.