I am looking for a bash or sed script (preferably a one-liner) with which I can insert a new line character after a fixed number of characters in huge text file.
views:
1396answers:
4
+4
A:
How about something like this? Change 20 is the number of characters before the newline, and temp.text is the file to replace in..
sed -e "s/.\{20\}/&\n/g" < temp.txt
Kristian
2009-07-27 09:15:47
works like a charm, thanks
rangalo
2009-07-27 09:29:54
no need for cat.
ghostdog74
2009-07-27 09:35:32
Fails if the file contains a '~' character
William Pursell
2009-07-27 10:05:42
Removed the cat and the "~" problem...
Kristian
2009-07-27 10:19:19
This inserts a newline after *every* 20 characters (per line of the original). If the original contains no newlines and you want a newline after only the first 20 characters, leave out the "g" (global) at the end. If you want this and the original contains newlines, you'll have to use a different solution.
Dennis Williamson
2009-07-27 10:45:55
+1
A:
if you mean you want to insert your newline after a number of characters with respect to the whole file, eg after the 30th character in the whole file
gawk 'BEGIN{ FS=""; ch=30}
{
for(i=1;i<=NF;i++){
c+=1
if (c==ch){
print ""
c=0
}else{
printf $i
}
}
print ""
}' file
if you mean insert at specific number of characters in each line eg after every 5th character
gawk 'BEGIN{ FS=""; ch=5}
{
print substr($0,1,ch) "\n" substr($0,ch)
}' file
ghostdog74
2009-07-27 09:34:35
A:
Append an empty line after a line with exactly 42 characters
sed -ie '/^.\{42\}$/a\
' huge_text_file
Chen Levy
2009-07-27 10:12:19
A:
Let N be a shell variable representing the count of characters after which you want a newline. If you want to continue the count accross lines:
perl -0777 -pe 's/(.{'$N'})/\1\n/sg' input
If you want to restart the count for each line, omit the -0777 argument.
William Pursell
2009-07-27 10:28:31