Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

shell script - insert line of text into file

  • 02-12-2010 11:23AM
    #1
    Registered Users, Registered Users 2 Posts: 2,353 ✭✭✭


    Hi guys,

    if ya can help be great.

    tryin to insert a line of text before a line of text saying "exit 0" on a file


    ____________________


    "my text"


    exit 0


    ___________________-


Comments

  • Moderators, Technology & Internet Moderators Posts: 1,338 Mod ✭✭✭✭croo


    I think sed might do what you want. Something like ...
    sed '/exit/ a myText goes here' yourFilename
    
    Now that would just modified the stream so you'd need to redirect to another new file
    sed '/exit/ a myText goes here' yourFilename>newFilename
    

    If you needed to edit in place, I think you might have to turn to awk... I am sure there are loads of examples on the web - google can always help with that!


  • Registered Users, Registered Users 2 Posts: 1,110 ✭✭✭Skrynesaver


    leave out ".bak" to make no save copy
     perl -pi.bak -e 's/(^\s*exit\s+0\s*$)/My Text\n$1/;' filename
    

    perl - obviously

    -p - print all lines
    -i edit in place
    .bak - extension to save backup as
    -e - execute the following
    's/(exit 0)/My Text\n$1/;' - substitute "exit 0" with "My Text, new line, exit 0"

    filename - the file to operate on.


  • Registered Users, Registered Users 2 Posts: 2,353 ✭✭✭Galway K9


    I tried the sed approach but wasnt outputting to file was just reading in life, inserting text and o/p to console.

    i piped the filename to another file and then moved to original(rename). worked a treat.


    Thanks


  • Moderators, Technology & Internet Moderators Posts: 1,338 Mod ✭✭✭✭croo


    leave out ".bak" to make no save copy
     perl -pi.bak -e 's/(^\s*exit\s+0\s*$)/My Text\n$1/;' filename
    

    perl - obviously

    -p - print all lines
    -i edit in place
    .bak - extension to save backup as
    -e - execute the following
    's/(exit 0)/My Text\n$1/;' - substitute "exit 0" with "My Text, new line, exit 0"

    filename - the file to operate on.
    I must learn perl!
    I know it's probably been around forever now but to me it's still the "new" scripting language :)


Advertisement