Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add 100 spaces at end of each line of a file in Unix

Tags:

shell

unix

awk

I have a file which is supposed to contain 200 characters in each line. I received a source file with only 100 characters in each line. I need to add 100 extra white spaces to each line now. If it were few blank spaces, we could have used sed like:

 sed 's/$/     /' filename > newfilename

Since it's 100 spaces, can anyone tell me is it possible to add in Unix?

like image 835
user1768029 Avatar asked Dec 06 '16 15:12

user1768029


People also ask

How do I add a space in Unix?

How it works: s/\(. \{1\}\)/\ /g will add a space, after each 1 character. So it will add a space, after each 2 characters.

How do you put a space between lines in shell script?

The G command appends a newline and the hold space to the end of the pattern space. Since, by default, the hold space is empty, this has the effect of just adding an extra newline at the end of each line. The prefix $! tells sed to do this on all lines except the last one.


2 Answers

If you want to have fixed n chars per line (don't trust the input file has exact m chars per line) follow this. For the input file with varying number of chars per line:

$ cat file
1
12
123
1234
12345

extend to 10 chars per line.

$ awk '{printf "%-10s\n", $0}' file | cat -e

1         $
12        $
123       $
1234      $
12345     $

Obviously change 10 to 200 in your script. Here $ shows end of line, it's not there as a character. You don't need cat -e, here just to show the line is extended.

like image 103
karakfa Avatar answered Sep 21 '22 16:09

karakfa


If you use Bash, you can still use sed, but use some readline functionality to keep you from manually typing 100 spaces (see manual for "Readline arguments").

You start typing normally:

sed 's/$/

Now, you want to insert 100 spaces. You can do this by prepending hitting the space bar with a readline argument to indicate that you want it to happen 100 times, i.e., you manually enter what would look like this as a readline keybinding:

M-1 0 0 \040

Or, if your meta key is the alt key: Alt+1 00Space

This inserts 100 spaces, and you get

sed 's/$/                                                                                                    /' filename

after typing the rest of the command.

This is useful for working in an interactive shell, but not very pretty for scripts – use any of the other solutions for that.

like image 41
Benjamin W. Avatar answered Sep 22 '22 16:09

Benjamin W.