[Solved] Replacing "\n1" with "\n"

Forum rules
Before you post please read this

[Solved] Replacing "\n1" with "\n"

Postby Onsen on Fri Oct 11, 2013 3:49 pm

Sometimes I want to accomplish something that seems like an easy thing to do, but when I try it out proves to be impossible. Like removing or editing a notification or playing Hi10p 1080p videos.


This time I want to write a script that finds some string and replaces it with some other string. Among others I want to replace "\n1" with "\n". (I also want to replace "\n2", "\n3", "\n4", "\n5", "\n6", "\n7", "\n8", "\n9" and "\n0" with "\n" and later "\n" with " " and after that "STRING" with "\n\n\nSTRING\n")

So I searched the internet and found stuff like,..

Code: Select all
sed -e '{:q;N;s/\n//g;t q}' file


Which does a good job removing "\n", but hilariously fails with what I want it to do. And for just removing "\n" there are shorter lines of code, I found out. (Of course, those won't work with strings.)

Code: Select all
#! /bin/sh

for f in /path/*.txt
do
sed -i '{:q;N;s/\n1//g;t q}' $f
done


This actually does what I want it to do..at least somewhat.. but it does so at random. Or maybe there is a pattern that I just can't figure out.


Input
1
11
111
1111
11111

1

11

111

1111

11111


What I get using gedit/pluma (without the loop)

1
1
11
111
1111



1

11

111

1111


What I actually get

1









11

111

1111


Of course, I also found out about perl and awk and about paste and tr, but I never got to the point where I could find something that finds "\n1" and replaces it with "\n". Except for my old approach that is using gedit/pluma, of course.

...what am I doing wrong?
Last edited by Onsen on Sun Oct 13, 2013 8:17 am, edited 1 time in total.
My introduction. Free Games for Linux.
User avatar
Onsen
Level 1
Level 1
 
Posts: 33
Joined: Tue Sep 11, 2012 9:54 am

Linux Mint is funded by ads and donations.
 

Re: Replacing "\n1" with "\n"

Postby Onsen on Sun Oct 13, 2013 8:17 am

Figured out how to do this on my own.

Code: Select all
#! /bin/sh
for f in /path/to/file.txt
do
sed -i ':a;N;$!ba;s/\n[0-9]/\n/g' "$f"
done


Easier to read version (what I used to play around and test things):

Code: Select all
sed -e ':a' \                
    -e 'N' \               
    -e '$!ba' \
    -e 's/\n[0-9]/\n/g' "$f             # deletes digit if it's the first character on the line"


I put all the possibilities (\n0, \n1, ... , \n9) into a single command using "\n[0-9]".
My introduction. Free Games for Linux.
User avatar
Onsen
Level 1
Level 1
 
Posts: 33
Joined: Tue Sep 11, 2012 9:54 am


Return to Scripts & Bash

Who is online

Users browsing this forum: No registered users and 2 guests