-2

After running command sed -i "/class MySQLPagedResultsajax/i Thing I Wish To Add;" /File/Location/

The result I get are as follows:

Thing I Wish To Add;class MySQLPagedResultsajax 

Whereas I want to achieve this:

Thing I Wish To Add;
class MySQLPagedResultsajax 

Please Help As I Want A Single Line Command Solution As This Needs To Be Done On Multiple Files And I Will Be Using Excel To Create Separate Commands For Each File.

  • 2
    That is odd and I can't reproduce it, `i` should insert a proper separate line (see the [GNU sed manual](https://www.gnu.org/software/sed/manual/sed.html#index-Inserting-text-before-a-line)). What version of sed are you using? – Benjamin W. Feb 25 '19 at 18:13
  • 1
    Possible duplicate of [Using sed, Insert a line above or below the pattern?](https://stackoverflow.com/q/11694980/608639) – jww Feb 25 '19 at 18:50
  • GNU sed version 4.2.1 Copyright (C) 2009 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, to the extent permitted by law. GNU sed home page: . General help using GNU software: . E-mail bug reports to: . Be sure to include the word ``sed'' somewhere in the ``Subject:'' field. – Rishi Sachdeva Feb 25 '19 at 19:59
  • I Want A Single Line Command Solution and hence this is not duplicate – Rishi Sachdeva Feb 25 '19 at 20:00

2 Answers2

0

Try this:

sed -i '/class MySQLPagedResultsajax/s/^/Thing I Wish To Add;\n/'

Or before you are sure, try this first and check the output on console:

sed -e '/class MySQLPagedResultsajax/s/^/Thing I Wish To Add;\n/'

s is the substitute command.
^ means the beginning of the line.
\n a newline.

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Til
  • 5,150
  • 13
  • 26
  • 34
  • I ran it and the results were still the same Thing I Wish To Add;class MySQLPagedResultsajax – Rishi Sachdeva Feb 25 '19 at 19:49
  • @RishiSachdeva I need to confirm this: You want a newline after `Thing I Wish To Add;`, before `class`, right? Also are you using these commands inside another environment, which is not directly inside bash/shell? Please try produce [mcve]. – Til Feb 26 '19 at 02:45
0

Just use awk for anything other than a simple s/old/new:

awk '/class MySQLPagedResultsajax/{print "Thing I Wish To Add;"} 1' file

add -i inplace to do pseudo-inplace editing with GNU awk like you can do pseudo-inplace editing with GNU sed by adding -i.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185
  • I could not use -i since i am not using the latest version of awk so i moved the output to a temporary file but the results are still the same Thing I Wish To Add;class MySQLPagedResultsajax – Rishi Sachdeva Feb 25 '19 at 20:03
  • 1
    Then you have some kind of control characters in your input or in your code or you're doing something else to block printing of newlines. Use `cat -v` to see control chars. – Ed Morton Feb 25 '19 at 20:08