Reputation: 2559
Good day to all,
I was wondering how to replace newline at specific line number.
So far I have done: [Linenumber=11]
sed ':a;N;$!ba;11s/\n//g'
Thanks in advance for any clue
Upvotes: 2
Views: 690
Reputation: 77145
Well if you know the line number then it is pretty straightforward in any language:
$ cat file
1
2
3
4
5
Using sed
:
$ sed '3{N;s/\n//;}' file
1
2
34
5
In sed
, you can use a number as pattern which will signify the line number. We can enclose action inside braces so that it only takes place when the pattern is true. Here 3
stands for the line 3. Inside the brace is our action which states, N
to append the next line to pattern space separated by a new line. At this time we have line 3\nline4
in our pattern space. We follow up with a simple substitution to replace the newline with nothing.
Using awk
:
$ awk 'NR==3{printf "%s", $0; next}1' file
1
2
34
5
awk
also comprises of pattern action statements. Here we are using NR==3
as our pattern. NR
is awk
built-in variable which holds the current line number. When the line number is 3 we ask awk
to do specific action. Our action is inside the braces. We use printf
which explicitly requires a newline character. next
allows us to move to the next line. 1
at the end is an awk
idiom that triggers the default action which is to print. For all lines which do not match our pattern, we print them as is. Since it uses print
it puts the newline for us.
Using perl
:
$ perl -pe 'chomp if $.==3' file
1
2
34
5
With perl
we use two options. -p
creates an implicit while(<>) { print }
loop to process each line of our file. -e
tells the perl
interpreter to execute the code that follows it. $.
in perl
holds the current line number. chomp
is a built-in function which removes the trailing newline. So when our line number is 3, we ask perl
to chomp
the newline for us. All other lines are printed as is.
Upvotes: 6
Reputation: 174786
Through perl,
perl -pe 's/\n// if $. == 11' file
To save the changes made,
perl -i -pe 's/\n// if $. == 11' file
Example:
$ cat file
1
2
3
4
$ perl -pe 's/\n// if $. == 3' file
1
2
34
Upvotes: 2