[Solved] How can I edit a file in Linux and add line breaks? [closed]


Assuming your data is in file named “file”:

sed -i 's/^\(.\{27\}\)\(.\{26\}\)\(.*\)/\1\n\2\n\3/g' file

sed is a very powerful tool for text processing, although not the easiest to use (but very easy when you want to make an example like this).
Here is the magic:

“-i” is a flag for “do this stuff for me”
in single quotes there is an instruction which consists four parts separated by slashes:
1. command: “s” – substitute
2. pattern: what do want to change
3. expected result: how do you want it to look like
4. range: “g” – global

The pattern is

\(.\{27\}\)\(.\{26\}\)\(.*\)

which means “make a group of first 27 characters in a line, then make another group of next 26 characters, and then make a first group of all the remaining character in the line”.

The expected result is

\1\n\2\n\3

which means “paste group one, paste new line, paste group two, paste new line, paste group three”.

To make it more clear you can put it in a script:

#!/bin/bash
COLUMN1=27
COLUMN2=26
FILENAME="file"     
sed -i "s/^\(.\{$COLUMN1\}\)\(.\{$COLUMN2\}\)\(.*\)/\1\n\2\n\3/g" file
exit 0

To make a script open any file editor (I use vim, other options are emacs, nano, kwrite, kate, geany, gedit… I can go on like that all day) and paste the code above. Save it, close the editor and issue

chmod +x script

to be able to execute it. You call scripts by

./script

Now you can provide arguments to your script, check if “file” exists, add more breaking points… but that is another story.

And then you can use a different tool, like awk (which I strongly recommend, but I usually use regex when I write in vim and sed is more like vim than awk, so I feel more comfortable with it).

More reading:

http://www.brunolinux.com/02-The_Terminal/Find_and%20Replace_with_Sed.html

http://www.grymoire.com/Unix/Sed.html

http://www.hcs.harvard.edu/~dholland/computers/awk.html

http://www.regular-expressions.info/

solved How can I edit a file in Linux and add line breaks? [closed]