Remove new line for a particular place

Hello All,

I have a text file which gets uploaded to tables using shells script. However before running that script I need to alter it, like in the below I have to firstly find the word 1234 and remove the new line from end of it.

1234,5678,fasfasasfsadf
abc

changes to

1234,5678,fasfasasfsadfabc

I have thought of using tr but I cannot make it use only the 1234 matches.

Regards
Sandeep

Hello Sandeep_sandy,

Welcome to forum, kindly use code tags for commands/codes/Inputs you are using in your posts, following may help you in same.
Let's say we have following input file then:

cat test199
1234,5678,fasfasasfsadf
abc
1234,5678,fasfasasfsadf
def
123i3486364,5678,fasfasasfsadf
abc

Then following may help in same.

awk '($0 ~ /^1234/){S=$0;getline;print S $0;S="";next} 1' test199

Output will be as follows.

1234,5678,fasfasasfsadfabc
1234,5678,fasfasasfsadfdef
123i3486364,5678,fasfasasfsadf
abc

Thanks,
R. Singh

1 Like

Another solution:

paste -d\0 - - <file|grep ^1234

Thanks a lot Ravinder.

But is it possible to use this command in a shell script and save the changes also, as it is not currently doing it.

You mean something like:

awk '($0 ~ /^1234/){S=$0;getline;print S $0;S="";next} 1' test199 > x$$ && cp x$$ test199; rm -f x$$
1 Like

or something along these lines:

{ rm test199; awk '($0 ~ /^1234/){S=$0;getline;print S $0;S="";next} 1' > test199; } < test199
sed '/^1234/{N;s/\n//}' file
1234,5678,fasfasasfsadfabc
1234,5678,fasfasasfsadfdef
123i3486364,5678,fasfasasfsadf
abc

This is an excellent idea as long as the file being processed is not a symbolic link, there are no other directory entries hard-linked to it, and you don't mind losing the some or all of your data if you run out of space on the filesystem or the awk script fails for some reason.

Thanks Don, this command indeed works but now I am getting a ^M (carriage return) at that place.

1234,5678,fasfasasfsadf
abc

turns to

1234,5678,fasfasasfsadf^Mabc

That's most certainly because your original file is not a *nix file but a windows file.

Using unzip -ja file.txt resolved the problem

Thanks everyone for your great help

[akshay@localhost tmp]$ cat file
1234,5678,fasfasasfsadf
abc
1234,5678,fasfasasfsadf
def
123i3486364,5678,fasfasasfsadf
abc
[akshay@localhost tmp]$ awk '/^1234/{ printf("%s",$0); next }1' file
1234,5678,fasfasasfsadfabc
1234,5678,fasfasasfsadfdef
123i3486364,5678,fasfasasfsadf
abc