0

I have a file A.txt and when I try to append a text to end of Nth line, it's printing by creating a new line, is there any command which will print in the same line without creating a newline?

A.txt

hi all       
how r u  
hows going

I want to a a string to the line Nth line ( line 2 in this example)

hi all   
how r u friend   
hows going

when I try the command I am getting in google, it's coming like below

$ cat a.txt
hi all  
how r u   
friend   
hows going
αғsнιη
  • 41,407
  • 3
    Would you like to repair your existing attempt, or are you open to alternatives? If the former, please include your command in an [edit] to the question. Thank you! – Jeff Schaller Apr 30 '21 at 02:12

2 Answers2

2

You can do it using sed as

sed '2s/.*/& friend/' a.txt

2s indicates that you want to substitute on line 2. .* will capture the entire line while & will print the line followed by new text.

If you want to update the file at the same time, you can use -i option with sed.

unxnut
  • 6,008
  • 6
    It might imply less work for the computer to replace only the end of the line:sed '2s/$/ friend/' a.txt –  Apr 30 '21 at 02:41
  • also can you chekc if you find a solution for this pls : https://unix.stackexchange.com/questions/647374/remove-a-text-from-the-nth-line-in-a-file – vijayakumar ponnusamy Apr 30 '21 at 03:20
2

with awk:

awk 'NR==2{ $0=$0 " friend" }1' infile >output

NR==2 means second line of input, $0 represent the current input line, 1 at the end, outputs the current input line with any changes made on it or not.

αғsнιη
  • 41,407