Insert string at line number nodejs

前端 未结 2 1130
清歌不尽
清歌不尽 2020-12-31 07:14

I have a file that I would like to modify. Is there a way to insert a string to a file at a specific line number? with NodeJS

I really thank you for helping me out<

2条回答
  •  清酒与你
    2020-12-31 07:46

    If you are on a Unix system then you probably want to use sed, like so to add some text to the middle of the file:

    #!/bin/sh
    text="Text to add"
    file=data.txt
    
    lines=`wc -l $file | awk '{print $1}'`
    
    middle=`expr $lines / 2`
    
    # If the file has an odd number of lines this script adds the text
    # after the middle line. Comment this block out to add before
    if [ `expr $lines % 2` -eq 1 ]
    then
      middle=`expr $middle + 1`
    fi
    
    sed -e "${middle}a $text" $file
    

    Note: above example is from here.

    With NodeJS it appears that there are some npm packages that might help, like sed.js, or replace.

提交回复
热议问题