简体   繁体   English

Bash脚本-Sed命令

[英]Bash Script - Sed Command

I created a script to add 100 space characters at the end of each line: 我创建了一个脚本,在每行末尾添加100个空格字符:

#!/bin/ksh
sed -i -e 's/\n/            - 100 spaces  -                         /' $1     

but it doesn't work and I think it is because of \\n . 但是它不起作用,我认为是因为\\n Any thoughts? 有什么想法吗?

Sed processes the content of the lines without the newline. sed处理行的内容而不使用换行符。 Your code never sees a newline, so it cannot replace it. 您的代码永远不会看到换行符,因此无法替换它。

Match the end of the string: 匹配字符串的结尾:

sed -i -e 's/$/ - 100 spaces - /' $1 

Although Karoly has already pointed out the error in your script, you could also save yourself typing 100 spaces by using a condition and break to make a sort of loop 尽管Karoly已经指出了脚本中的错误,但您也可以通过使用条件并中断以进行某种循环来节省键入100个空格的时间

sed ':1;/ \{100\}$/!{s/$/ /;b1}' file

Will print 100 space at the end of the line 将在行尾打印100个空间

If there are already spaces at the end and you want to add 100 如果末尾已经有空格,并且您想添加100

sed 's/$/1/;:1;/1 \{100\}$/!{s/$/ /;b1};s/1\( *\)$/\1/' file

Just a suggestion to avoid typing 100 spaces (although I'm sure that by this time, you already have!) - use perl: 只是建议避免输入100个空格(尽管我确定到现在为止,您已经拥有了!)-使用perl:

perl -pe 's/$/" " x 100/e' file

As the other answers have stated, this matches the end of the line and replaces with 100 spaces, using the e modifier to allow you to write " " x 100 and let perl do the work for you. 正如其他答案所指出的那样,这与行的末尾匹配并替换为100个空格,使用e修饰符允许您编写" " x 100然后让perl为您完成工作。

As with sed, you can modify the file in-place using the -i switch - as with sed, I'd suggest using something like -i.bak to create a backup file file.bak . 与sed一样,您可以使用-i开关就地修改文件-与sed一样,我建议使用-i.bak类的-i.bak来创建备份文件file.bak

Could be the \\n as that's undefined by POSIX and so implementation dependent across seds but you also say you want add spaces to the end of a line while your script is trying to replace the end of line with spaces. 可能是\\n ,因为POSIX未定义\\n ,因此实现依赖于sed,但您也说要在脚本试图用空格替换行尾时在行尾添加空格。

In any case this is not a job for sed, just use [s]printf("%100s","") in awk to create a string of 100 blanks, eg: 无论如何,这都不是sed的工作,只需在awk中使用[s]printf("%100s","")创建一个包含100个空格的字符串,例如:

$ echo "foo bar" | awk '{printf "%s%10s%s\n", $1, "", $2}'
foo          bar

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM