0

I created a script to add 100 space characters at the end of each line:

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

but it doesn't work and I think it is because of \n. Any thoughts?

4 Answers 4

2

Sed processes the content of the lines without the newline. Your code never sees a newline, so it cannot replace it.

Match the end of the string:

sed -i -e 's/$/ - 100 spaces - /' $1 
Sign up to request clarification or add additional context in comments.

Comments

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

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

Will print 100 space at the end of the line

If there are already spaces at the end and you want to add 100

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

5 Comments

But it will not add 100 if there were already some; it will stop when there are 100 spaces.
@tripleee added one for that.
Or you could use printf: sed "s/\$/$(printf ' %.0s' {1..100})/" file
@A.Danischewski Yep! i try to avoid embedding commands in sed though as it tends to be a bit flaky.
@123 Yea, if you open that style door it can turn into a can of worms. You could programmatically generate it with an echo "sed \"s/\$/$(printf ' %.0s' {1..100})/\"" and I would put a comment above what the space count is so you don't have to waste any time later.
0

Just a suggestion to avoid typing 100 spaces (although I'm sure that by this time, you already have!) - use 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.

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.

Comments

0

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.

In any case this is not a job for sed, just use [s]printf("%100s","") in awk to create a string of 100 blanks, e.g.:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.